Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quit the C++ application in Qt QML

Tags:

c++

qt

qml

according to the Qt qml Type documentation

quit()

This function causes the QQmlEngine::quit() signal to be emitted. Within the Prototyping with qmlscene, this causes the launcher application to exit; to quit a C++ application when this method is called, connect the QQmlEngine::quit() signal to the QCoreApplication::quit() slot.

so in order to quit the C++ application in QML i have to call this

 Qt.quit()

inside the QML files, but that only quits the QML engine i need to close the C++ application also.

here is my attempt

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

    QScopedPointer<NFCclass> NFC (new NFCclass);

    QQmlApplicationEngine engine;


    QObject::connect(engine, QQmlEngine::quit(), app,  QCoreApplication::quit()); 
// here is my attempt at connecting based from what i have understood in the documentation of signal and slots


    engine.rootContext()->setContextProperty("NFCclass", NFC.data());
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

Thank you very much if you can help me :)

I think its because i dont know the object of QtCore thats why that line throws an error

=========================================================================== edit:

Answer given by eyllanesc works.

but when i execute Qt.quit() in on completed it does not quit. It works on the button though

ApplicationWindow {
    id:root
    visible: true
    width: 480
    height: 640
    title: qsTr("Hello World")

    Component.onCompleted: {
       Qt.quit()
    }

    Button{onClicked: Qt.quit()}

}
like image 606
Jake quin Avatar asked Aug 12 '18 15:08

Jake quin


1 Answers

You have to learn to use the new connection syntax in Qt, in your case it is the following:

QObject::connect(&engine, &QQmlApplicationEngine::quit, &QGuiApplication::quit);

Update:

A workaround for the second case is to use Qt.callLater()

ApplicationWindow {
    id:root
    visible: true
    width: 480
    height: 640
    title: qsTr("Hello World")

    Component.onCompleted: {
         Qt.callLater(Qt.quit)
    }
}
like image 127
eyllanesc Avatar answered Oct 16 '22 20:10

eyllanesc