c++eventsqmlexit

QML: Asking confirmation before closing application


I have a QtQuick application. When the user tries to close the application, I want an "Are you sure?" window to pop up.

My main C++ class has this:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

And my main QML class has an application window:

ApplicationWindow {
    id: root
    ...
}

Where and how would I catch the close event? I read about overriding closeEvent() from QMainWindow method or something, but I don't have a QMainWindow and I don't know where I'd put that code.

So I'd like to know how to prevent the app from closing and have something else happen instead, and how I'd close the app later when the user clicks "ok" in the confirmation dialog.

As far as I can see, the ApplicationWindow's "onClosing" only allows me to do some clean up before the inevitable close, but it doesn't prevent the close (please correct me if I'm wrong)


Solution

  • I solved it.

    ApplicationWindow {
        id: root
        onClosing: close.accepted = false
    }
    

    This prevents the app from closing.

    root.close()
    

    This closes the app.