c++ - 在程序启动时选择不同的 QMainWindow 但面临奇怪的 QMessageBox exec() 行为
问题描述
我正在开发一个简单的 Qt Widget 应用程序,其中我有 2 个不同的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();
}
推荐阅读
- java - 日期和时间戳列之间的 JpaRepository @Query 比较不起作用
- javascript - 如何在多个控制器中使用 API 响应
- kotlin - AcceptHeaderLocaleResolver - 仍然不清楚如何使用它
- java - Using lists as columns results in bad performance - JPA
- c# - 如何在代码中维护 xml 文件的树结构并访问“子标签”?
- eclipse - 在 Eclipse 中启动 Tomcat 服务器时出现 404
- cakephp - CK 编辑器编辑页面未显示 youtube 嵌入代码
- python - 字典变量和“for”循环
- javascript - 如何通过文本输入使全局变量可变
- c++ - 避免在循环中使用 if 条件的最佳方法是什么?