QML: Asking confirmation before closing application

Viewed 4702

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)

3 Answers

I solved it.

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

This prevents the app from closing.

root.close()

This closes the app.

import QtQuick 2.13
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.13
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.3

ApplicationWindow  {
   property bool closing: false

   MessageDialog {
      id: exitMessageDialogId
      icon: StandardIcon.Question
      text: "Are you sure to exit?"
      standardButtons: StandardButton.Yes | StandardButton.No
      onYes: {
         closing = true
         mainWindowId.close()
      }
   }
   onClosing: {
      close.accepted = closing
      onTriggered: if(!closing) exitMessageDialogId.open()
   }

   id: mainWindowId
}

In this case it just close current window.

//use Qt 5.11.2 // for android y desktop

import QtQuick 2.9
import QtQuick.Controls 2.4
import QtQuick.Layouts 1.3
import QtQuick.Dialogs 1.2

ApplicationWindow {

    title: qsTr("xxxx xxxx")

    id: mainWindow
    visible: true


    //desision para salir
    MessageDialog {
        id: messageDialogQuit
        title: "Deseas salir?"
        icon: StandardIcon.Question
        text: "xxxxxxxxxxxxxxxxxxxxxxxxx."

        standardButtons: StandardButton.Yes |StandardButton.No
        //        Component.onCompleted: visible = true
        onYes: Qt.quit()
        //        onNo: console.log("didn't copy")
    }

    onClosing:{
        close.accepted = false
        onTriggered: messageDialogQuit.open()
    }

    menuBar: MenuBar {
        id: m_menu
        LayoutMirroring.enabled: true
        LayoutMirroring.childrenInherit: true
        anchors.left: parent.left
        Menu {
            title: qsTr("File")
            MenuItem {
                text: qsTr("Exit")
                onTriggered: messageDialogQuit.open()

            }

        }

    }
    width: 400
    height: 300

}
Related