c++ - QML:退出 QApplication 时关闭所有 QWidget

标签 c++ qt qml qt5 qwidget

我有一个 Qt 程序,它使用 QApplication 作为其主窗口,并且还可能生成许多 QMessageBox 小部件。当 QApplication 主窗口退出时,我需要关闭所有这些 QMessageBox 对话框。但是,我无法使用任何正常的回调,因为 QMessageBox 似乎阻止了 onDestruction() 信号。当我单击 X 退出 QApplication 时,它的窗口消失,但 onDestruction() 符号仅在最后一个 QMessageBox 退出时才会触发。请让我知道执行此操作的正确方法。

编辑:

这是我的 main.cpp:

int main(int argc, char* argv[]) {
    QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    Application app(argc, argv);
    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty("applicationVersion", VER_FILEVERSION_STR);
    engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    int retval = app.exec();
    qInstallMessageHandler(0);

    return retval;
}

这是我实例化 QMessageBox 的方法:

QMessageBox* errorD = new QMessageBox();
errorD->setStandardButtons(QMessageBox::Ok);
errorD->setDefaultButton(QMessageBox::Ok);
errorD->setModal(false);
errorD->setWindowTitle(title);
errorD->setText(msg);
// We reset when closed
QObject::connect(errorD, &QMessageBox::destroyed, [=]() { printf("QMBox destroyed.");});
errorD->raise();
errorD->activateWindow();
errorD->show();
QApplication::processEvents();

最佳答案

一个可能的解决方案是创建一个 Helper 来调用关闭小部件的函数,这应该在 onClosing 中调用:

ma​​in.cpp

class Helper : public QObject
{
    Q_OBJECT
    QWidgetList widgets;
  public:
    Q_INVOKABLE void closeAllWidgets(){
        for(QWidget *w: widgets)
            w->close();
    }
    void addWidget(QWidget *w){
        widgets<<w;
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    Helper helper;
    engine.rootContext()->setContextProperty("helper", &helper);
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    for(int i=1; i < 5; i++){
        QMessageBox* errorD = new QMessageBox();
        helper.addWidget(errorD);
        [...]

ma​​in.qml

import QtQuick 2.7
import QtQuick.Controls 2.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    onClosing: helper.closeAllWidgets();
}

在以下链接中,您将找到 example

关于c++ - QML:退出 QApplication 时关闭所有 QWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47338259/

相关文章:

c++ - get派生类访问彼此的成员数据和函数

c++ - 如何从 std::map 中删除一个键值对

c++ - 如何修改 Qt 样式表?

c++ - 比较 C 和 C++ 中的结构

qt - ScrollView 中的矩形不可见

c++ - Qt 部署的可执行文件打开空白应用程序

c++ - 使用 QML 绘制图形项目的最佳方式是什么?

c++ - 交叉编译Qt for ARM时出错

c++ - 如何将鼠标坐标转换为 "mm"

c++ - 从 C++ 访问 QML 的 LayoutMirroring 附加属性