在主窗口之前显示对话框

时间:2013-05-06 12:19:41

标签: c++ qt

我有一个窗口应用程序,只有在激活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;
    }
    (...)
}

2 个答案:

答案 0 :(得分:1)

尝试一个没有指向主窗口的消息框,如下例所示:

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初始化之后)。

答案 1 :(得分:0)

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

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

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