QML:退出QApplication时关闭所有QWidgets

时间:2017-11-16 20:08:46

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

1 个答案:

答案 0 :(得分:2)

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

<强>的main.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);
        [...]

<强> main.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