简体   繁体   中英

QML: Close all QWidgets when QApplication is exited

I have a Qt program that uses QApplication for its main window and also spawns potentially many QMessageBox widgets. I need to close all of these QMessageBox dialogs when the main QApplication window is quit. However, I am unable to use any of the normal callbacks as the QMessageBox's seem to block the onDestruction() signal. When I click the X to quit the QApplication, its window goes away, but the onDestruction() symbol is only fired when the last QMessageBox is quit. Please let me know the right way to do this.

Edit:

Here's my 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;
}

And here's how I instantiate a 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();

A possible solution is to create a Helper that calls a function that closes the widgets, and this should be called in 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();
}

In the following link you will find an example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM