如何在 Qt QML 中退出 C++ 应用程序

2022-01-19 00:00:00 qt qml c++

根据 Qt qml Type 文档

according to the Qt qml Type documentation

退出()

这个函数导致 QQmlEngine::quit() 信号被发出.在使用 qmlscene 进行原型设计时,这会导致启动器申请退出;退出 C++ 应用程序时此方法调用时,将 QQmlEngine::quit() 信号连接到QCoreApplication::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.

所以为了退出 QML 中的 C++ 应用程序,我必须调用它

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

 Qt.quit()

在 QML 文件中,但这只会退出 QML 引擎,我还需要关闭 C++ 应用程序.

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

这是我的尝试

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 :)

我认为是因为我不知道 QtCore 的对象,这就是该行抛出错误的原因

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

==============================================================================

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

eyllanesc works给出的答案.

Answer given by eyllanesc works.

但是当我在完成时执行 Qt.quit() 时它不会退出.但它适用于按钮

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()}

}

推荐答案

你要学会使用新的连接语法在 Qt 中,您的情况如下:

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);

更新:

第二种情况的解决方法是使用 <代码>Qt.callLater()

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)
    }
}

相关文章