Reputation: 2002
I have 3 buttons on QMessageBox added by QMessageBox::addButton() method. Is it possible to prevent closing the message box if a button has been clicked? By default every button closes the window, but I don't want to do it for one button.
Upvotes: 7
Views: 3792
Reputation: 1
On my experience, using button.disconnect()
has worked in the way of preventing the dialog from closing but has had an impact on the widget layout, particularly on the button ordering in the UI.
Upvotes: 0
Reputation: 683
Thanks to @Albert's Answer, I found that this also possible in python:
messagebox = QMessageBox()
button = QPushButton("This button will not close anything")
messagebox.addButton(button, QMessageBox.ButtonRole.NoRole)
button.disconnect()
Upvotes: 0
Reputation: 1051
One interesting way to approach it that worked for me is to completely disconnect the signals for the target button created, and then re-add the intended functionality. This won't work for everyone, especially if the button isn't created this way and/or you still want to close the dialog correctly. (There might be a way to add it back and/or simulate the behavior with QDialog::accept
, QDialog::reject
, QDialog::done
- haven't tried yet.)
Example:
QMessageBox *msgBox = new QMessageBox(this);
QAbstractButton *doNotCloseButton = msgBox->addButton(tr("This button will not close anything"), QMessageBox::ActionRole);
// Disconnect all events - this will prevent the button from closing the dialog
doNotCloseButton->disconnect();
connect(doNotCloseButton, &QAbstractButton::clicked, this, [=](){ doNotCloseButton->setText("See? Still open!"); });
Upvotes: 6
Reputation: 31
Just had the same problem but I wanted to add a checkbox and it kept closing the dialog on clicked even with the ButtonRole
set to QMessageBox::ActionRole
(tried others too). For this scenario I just called blockSignals(true)
on the QCheckBox
and now it allows check/uncheck behaviour without closing the dialog. Luckily QCheckBox
works fine without signals but assume you want a signal from your button.
They should likely add a new role that doesn't close the dialog as it's a pain to derive a class for simple customizations.
Upvotes: 3
Reputation: 13807
I looked through the addButton()
functions overloads, but there is no custom behavior for the buttons you add with this method. They will behave like the standard buttons on a messagebox should.
However if you want to create a fully customizable dialog, then your best option is to extend the QDialog
class and use whatever controlls you like on it.
Upvotes: 2
Reputation: 5555
If you can get a pointer to the QMessageBox
widget, you can try to install a QObject::eventFilter
on it which filters the QEvent::Close
.
Upvotes: 3