Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make QMessageBox non-modal?

I'm trying to create a non-modal QMessageBox:

QMessageBox msgBox( pParentWindow );
msgBox.setWindowModality(Qt::WindowModal);
msgBox.setIcon( QMessageBox::Warning );
msgBox.setText( headerMsg.c_str() );
QAbstractButton *btnCancel =  msgBox.addButton( "Cancel", QMessageBox::RejectRole );
msgBox.exec();

(this is a simplified example). The problem is, this is still modal: I can move another (non-parent) dialog, but I can't close it. I also tried:

msgBox.setModal(false);

but the msgBox still prevents me from closing the other dialog. What am I missing? Perhaps the problem is with exec()?

like image 338
TT_ Avatar asked Dec 24 '22 09:12

TT_


1 Answers

If you want nonmodal (non-blocking) dialog/MessageBox, then yes don't use exec(), and just show() the messagebox while setting setModal as false. but if you do that from within a slot/function, the messagebox as declared in your example won't persist because its scope (lifetime) expires by the end of slot/method execution. Therefore you need to extend its lifetime either using a pointer or make it member. For instance, you could have this slot:

void MainWindow::popMessageBox()
{
 QMessageBox *msgBox = new QMessageBox(pParentWindow);
 msgBox->setIcon( QMessageBox::Warning );
 msgBox->setText(headerMsg.c_str());
 QPushButton *btnCancel =  msgBox->addButton( "Cancel", QMessageBox::RejectRole );
 msgBox->setAttribute(Qt::WA_DeleteOnClose); // delete pointer after close
 msgBox->setModal(false);
 msgBox->show();
}

As of my testing, closing other dialog is possible while the messagebox is show still, but if it prevents you from processing/using other windows until cancel is clicked! in that case you would need to start it in separate thread, and continue interacting with other window/dialog.

like image 177
Mohammad Kanan Avatar answered Jan 13 '23 15:01

Mohammad Kanan