在程序启动时选择不同的QMainWindow,但面临奇怪的QMessageBox exec()行为



我正在开发一个简单的Qt Widget应用程序,其中有两个不同的QMainWindow类要向用户显示(目前只实现了一个)。

我的想法是显示一个带有自定义按钮的消息框,询问用户要执行的程序模式。

我想出了下面的代码,但我面临着奇怪的问题。如果你做一个简单的qt小部件项目,你可以很容易地尝试这个代码。

所以问题是,消息框显示正确,按钮显示正确。当用户选择"调试模式"时,正确的MainWindow将显示几分之一秒,然后消失!但该程序仍然开放,将无法返回!

对于"操作模式",会显示关键消息框,但当用户单击ok时,所有消息框都会消失,但再次未到达返回代码!

"退出"选项也是如此。。。

#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <QAbstractButton>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// At the start of the progam ask user which mode to show
QMessageBox msgBoxModeSelection;
msgBoxModeSelection.setIcon(QMessageBox::Question);
msgBoxModeSelection.setText("Please select the program mode:");
QAbstractButton* btnModeDebug = msgBoxModeSelection.addButton(
"Debug Mode", QMessageBox::YesRole);
QAbstractButton* btnModeOperation = msgBoxModeSelection.addButton(
"Operation Mode", QMessageBox::NoRole);
QAbstractButton* btnModeExit = msgBoxModeSelection.addButton(
"Exit", QMessageBox::RejectRole);
msgBoxModeSelection.exec();
// Check which mode is being selected by user and continue accordingly
if(msgBoxModeSelection.clickedButton() == btnModeDebug) {
MainWindow w;
w.show();
} else if(msgBoxModeSelection.clickedButton() == btnModeOperation){ // Operation Mode
//TODO implement...for now just inform user that it is not implemented
QMessageBox::critical(nullptr, "Error", "Operation Mode is not yet implemented");
return a.exec();
} else if(msgBoxModeSelection.clickedButton() == btnModeExit){ // Just exit
// Just exit the program
QMessageBox::critical(nullptr, "Goodbye!", "Sorry to see you go :(");
return a.exec();
}
return a.exec();
}

因此,基本上程序消失了,但它仍然以某种方式打开并正在处理中。终止它的唯一方法是停止调试器或从操作系统中终止其进程。

因此,我希望显示正确的表单,因为没有涉及messageBox,并且程序的返回代码和退出再次正常!

您的MainWindow只存在于if语句中。因此,一旦它出现并离开其范围,它就会被销毁。

将其更改为例如:

MainWindow w;
if(msgBoxModeSelection.clickedButton() == btnModeDebug) {
w.show();
}

if(msgBoxModeSelection.clickedButton() == btnModeDebug) {
MainWindow w;
w.show();
return a.exec();
}

最新更新