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

Selecting different QMainWindow at program startup but facing strange QMessageBox exec() behavior

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

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

我想出了下面的代码,但我遇到了奇怪的问题。如果您制作一个简单的 qt widget 项目,您可以轻松地尝试此代码。

所以问题是,正在显示消息框并且正确显示按钮。当用户选择 "Debug Mode" 时,正确的 MainWindow 会出现几分之一秒然后消失!但程序保持打开状态,return 将无法到达!

对于 "Operation Mode",显示了关键消息框,但是当用户单击 ok 时,所有消息框都消失了,但再次 return 代码未达到!

"Exit" 选项也是如此...

#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 涉及并且程序的 return 代码和退出再次正常!

您的 MainWindow 仅存在于 if 语句中。所以它一出现并离开它的范围就会被破坏。

将其更改为例如:

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

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