c++ - 在主窗口之前显示对话框

标签 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;
    }
    (...)
}

最佳答案

像这个例子一样尝试一个没有指针指向主窗口的消息框:

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/

相关文章:

python - 如何在 PyQt/Python 中切换布局? (先进的)

c++ - QSortFilterProxyModel 和动态排序

c# - 为 C# 包装 native DLL

c++ - 如何编译具有 'wlanapi.h' 和 'windows.h' 依赖项的 C++ 代码

c++ - 使用 g++ 构建的 C++ 中的运行时数组边界检查

c++ - 是否可以在 OS X 上重新设置 QProgressBar 的样式?

qt - QML 中的尺寸是与设备无关的像素吗?

c++ - 检测 WM_MOUSEMOVE 是否由触摸/笔引起

c++ - 通过引用传递 vector

linux - 将现有的 OpenCV 应用程序包含到 Qt GUI 中