根据Qt qml类型文档
退出()
此函数导致发出QQmlEngine :: quit()信号。在使用qmlscene进行原型制作时,这会导致启动器应用程序退出;要在调用此方法时退出C ++应用程序,请将QQmlEngine :: quit()信号连接到 QCoreApplication :: quit()插槽。
因此,为了退出QML中的C ++应用程序,我必须调用它
Qt.quit()
Run Code Online (Sandbox Code Playgroud)
在QML文件中,但这仅退出QML引擎,我也需要关闭C ++应用程序。
这是我的尝试
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();
}
Run Code Online (Sandbox Code Playgroud)
如果可以帮助我,非常感谢您:)
我认为是因为我不知道QtCore的对象,这就是为什么该行引发错误
================================================== ========================编辑:
eyllanesc给出的答案有效。
但是当我在完成时执行Qt.quit()时,它不会退出。它可以在按钮上工作
ApplicationWindow {
id:root
visible: true
width: 480
height: 640
title: qsTr("Hello World")
Component.onCompleted: {
Qt.quit()
}
Button{onClicked: Qt.quit()}
}
Run Code Online (Sandbox Code Playgroud)
eyl*_*esc 10
您必须学习在 Qt 中使用新的连接语法,在您的情况下,它如下:
QObject::connect(&engine, &QQmlApplicationEngine::quit, &QGuiApplication::quit);
Run Code Online (Sandbox Code Playgroud)
更新:
第二种情况的解决方法是使用 Qt.callLater()
ApplicationWindow {
id:root
visible: true
width: 480
height: 640
title: qsTr("Hello World")
Component.onCompleted: {
Qt.callLater(Qt.quit)
}
}
Run Code Online (Sandbox Code Playgroud)