From 5827ee5ffc429591648019b6f19b72bf4207fe7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tor=20Arne=20Vestb=C3=B8?= Date: Mon, 14 Nov 2022 22:08:58 +0100 Subject: QMessageBox: Resolve button title from button role if title is empty Our tst_QMessageBox tests exhibits many cases of adding a button to a message box without a specific title, e.g.: QPushButton *button = new QPushButton; msgBox.addButton(button, QMessageBox::DestructiveRole); This results in buttons without a title, which for a native backend may be an error. We mitigate the issue by resolving a default button title based on its role. Change-Id: Ib8a15818a83021771793ea85a5f782690fe677ec Reviewed-by: Richard Moe Gustavsen --- src/widgets/dialogs/qmessagebox.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src') diff --git a/src/widgets/dialogs/qmessagebox.cpp b/src/widgets/dialogs/qmessagebox.cpp index 581bc3f93c..d1af4b2842 100644 --- a/src/widgets/dialogs/qmessagebox.cpp +++ b/src/widgets/dialogs/qmessagebox.cpp @@ -28,6 +28,7 @@ #include #include #include "private/qabstractbutton_p.h" +#include #ifdef Q_OS_WIN # include @@ -203,6 +204,7 @@ public: QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton); static QPixmap standardIcon(QMessageBox::Icon icon, QMessageBox *mb); + static QMessageBox::StandardButton standardButtonForRole(QMessageBox::ButtonRole role); QLabel *label; QMessageBox::Icon icon; @@ -843,6 +845,19 @@ void QMessageBox::addButton(QAbstractButton *button, ButtonRole role) if (!button) return; removeButton(button); + + if (button->text().isEmpty()) { + if (auto *platformTheme = QGuiApplicationPrivate::platformTheme()) { + if (auto standardButton = QMessageBoxPrivate::standardButtonForRole(role)) + button->setText(platformTheme->standardButtonText(standardButton)); + } + + if (button->text().isEmpty()) { + qWarning() << "Cannot add" << button << "without title"; + return; + } + } + // Add button to native dialog helper, unless it's the details button, // since we don't do any plumbing for the button's action in that case. if (button != d->detailsButton) { @@ -854,6 +869,21 @@ void QMessageBox::addButton(QAbstractButton *button, ButtonRole role) d->autoAddOkButton = false; } +QMessageBox::StandardButton QMessageBoxPrivate::standardButtonForRole(QMessageBox::ButtonRole role) +{ + switch (role) { + case QMessageBox::AcceptRole: return QMessageBox::Ok; + case QMessageBox::RejectRole: return QMessageBox::Cancel; + case QMessageBox::DestructiveRole: return QMessageBox::Discard; + case QMessageBox::HelpRole: return QMessageBox::Help; + case QMessageBox::ApplyRole: return QMessageBox::Apply; + case QMessageBox::YesRole: return QMessageBox::Yes; + case QMessageBox::NoRole: return QMessageBox::No; + case QMessageBox::ResetRole: return QMessageBox::Reset; + default: return QMessageBox::NoButton; + } +} + /*! \since 4.2 \overload -- cgit v1.2.3