如何使 QMessageBox 成为非模态的?

How to make QMessageBox 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();

(这是一个简化的例子)。问题是,这仍然是模态的:我可以移动另一个(非父)对话框,但我无法关闭它。我也试过:

msgBox.setModal(false);

但是 msgBox 仍然阻止我关闭另一个对话框。我错过了什么? 也许问题出在 exec() 上?

如果你想要 nonmodal (non-blocking) dialog/MessageBox,那么是的,不要使用 exec(),并且在设置 show() 时只使用消息框 setModalfalse。但是如果您在 slot/function 中执行此操作,则示例中声明的消息框将不会持续存在,因为它的范围(生命周期)在 slot/method 执行结束时到期。因此,您需要使用指针或使其成为成员来延长其生命周期。例如,你可以有这个插槽:

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();
}

根据我的测试,当消息框仍然显示时可以关闭其他对话框,但如果它阻止您 processing/using 其他 windows 直到 cancel 被点击!在这种情况下,您需要在单独的 线程 中启动它,并继续与其他 window/dialog.

进行交互