我有一个窗口应用程序,它在 QMainWindow 激活之前显示信息对话框后崩溃。
仅当传递的数据无效时才会显示信息对话框,但它可能是用户交互(文件选择/拖动)或作为参数传递,这会导致问题。我应该什么时候/如何显示这样的错误对话框?
注意:当仅显示对话框时(使用 show() 方法而不是 exec())它不会崩溃,但即使使用 setModal( true ) 也会立即丢弃对话框。
有什么想法吗?谢谢,
编辑:
部分代码:
int WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, LPSTR lpCmdLine, int nShowCmd)
{
QApplication app(__argc, __argv);
MBViewer viewer;
viewer.show();
return app.exec();
}
MBViewer::MBViewer()
{
setAcceptDrops(true);
m_ui.setupUi(this);
m_viewer = new Viewer_Widget();
m_ui.preview_layout->addWidget(m_viewer);
parse_parameters();
connect_controls();
connect_actions();
}
void MBViewer::connect_controls()
{
(...)
connect( m_viewer, SIGNAL( view_initialized()), this, SLOT( open_file() ));
(...)
}
void MBViewer::open_file()
{
// somefile is set in parse_parameters or by user interaction
if (!somefile.is_valid()) {
m_viewer->reset();
// This will crash application after user clicked OK button
QMessageBox::information( this, "Error", "Error text", QMessageBox::Ok );
return;
}
(...)
}
最佳答案
像这个例子一样尝试一个没有指针指向主窗口的消息框:
QMessageBox msgBox;
msgBox.setText(text.str().c_str());
msgBox.setIcon(QMessageBox::Question);
QPushButton *speed = msgBox.addButton("Speed optimization", QMessageBox::AcceptRole);
QPushButton *memory = msgBox.addButton("Memory optimization", QMessageBox::AcceptRole);
QPushButton *close = msgBox.addButton("Close", QMessageBox::RejectRole);
msgBox.setDefaultButton(speed);
msgBox.exec();
if (msgBox.clickedButton() == memory)
return true;
if (msgBox.clickedButton() == close)
exit(4);
它甚至可以在创建任何窗口之前工作(但在 QApplication 初始化之后)。
关于c++ - 在主窗口之前显示对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16398639/