在主窗口前显示对话框

Show dialog before main window

本文关键字:显示 对话框 窗口      更新时间:2023-10-16

我有一个窗口应用程序,只有在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初始化之后)。

当你调用app.exec()时,它启动主消息处理程序循环,这是在你开始显示对话框之前需要运行的。当与exec一起使用时,QMessageBox是一个模态对话框,因此将阻止app.exec函数被调用。因此,很可能在初始化消息处理程序之前发送消息,因此观察到崩溃。

当使用show()时,允许执行app.exec,这就是为什么不会发生崩溃的原因。

如果你在启动时想要一个模态MessageBox,你需要在创建/初始化消息处理程序之后启动它。这不是最干净的方法,但您可以尝试在计时器上启动它,以延迟对exec的调用。