How to prevent QMessageBox from closing after clicking a button

I have 3 buttons on a QMessageBox added by the QMessageBox :: addButton () method. Is it possible to prevent the message box from closing if the button is pressed? By default, each button closes the window, but I do not want to do this with one button.

EDIT: Why is it down?

+4
source share
4 answers

I looked at overloads of addButton() functions, but there are no custom actions for the buttons you add using this method. They will behave like standard buttons in the message box.

However, if you want to create a fully customizable dialog, then your best option is to extend the QDialog class and use whatever you like on it.

+1
source

If you can get a pointer to a QMessageBox widget, you can try setting QObject::eventFilter on it, which filters QEvent::Close .

+3
source

I had the same problem, but I wanted to add a checkbox, and it closed the dialog when I clicked the ButtonRole button on QMessageBox::ActionRole (also tried others). For this scenario, I just called blockSignals(true) in the QCheckBox , and now it allows you to check / cancel the behavior without closing the dialog. Fortunately, the QCheckBox works fine without signals, but suppose you need a signal from your button.

They should probably add a new role that does not close the dialog, since it is a pain to get a class for simple settings.

+3
source

One interesting way to get close to it, which worked for me, is to completely turn off the signals for the created target button, and then add the intended functionality again. This will not work for everyone, especially if the button is not created in this way and / or you still want to close the dialog box correctly. (Perhaps there is a way to add it back and / or simulate the behavior using QDialog::accept , QDialog::reject , QDialog::done - have not tried it 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!"); }); 
0
source

All Articles