在 Component.onCompleted 之前初始化 QML 信号
Initialize QML-signal before Component.onCompleted
我遇到以下问题:
我写了一个 qml-GUI 和一个接口 class 来通过连接 qml 端的信号和 c++ 端的槽来与一些 C++ 代码通信。基于事件或按钮的触发器工作正常,但我需要一个必须在启动时直接触发的信号。我使用 ApplicationWindow
中的 Component.onCompleted
进行了尝试。然而,
the output "setInitDrone() called" is generated but
getInitDrone()
is never reached.
The QT documentation says:
"The order of running the onCompleted handlers is undefined."
当我尝试发送信号时,是否可以确保信号已经初始化,或者有没有其他方法可以代替 Component.onCompleted?
谢谢你的帮助!
main.qml:
ApplicationWindow{
id: appWindow
visible: true
minimumHeight: 800
minimumWidth: 700
visibility: Window.Maximized
signal setInitDrone()
Component.onCompleted: {
setInitDrone()
print("setInitDrone() called")
}
}
qml_cpp_interface.cpp:
void Qml_cpp_interface::getInitDrone(){
qDebug() << "Cpp initDrone received";
flightserver.init();
}
groundstation.cpp:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
//Connect with C++ code
QObject *item = engine.rootObjects().first();
Qml_cpp_interface qml_cpp_interface;
QObject::connect(item, SIGNAL(setInitDrone()), &qml_cpp_interface,SLOT(getInitDrone()));
return app.exec();
你做错了,你应该从 QML 访问 C++,而不是从 C++ 访问 QML。
向 QML 公开 Qml_cpp_interface
,因为公开核心逻辑接口是有意义的。由于您正在进行初始化,因此您甚至不需要信号,因为据推测,您只需要初始化一次,这就是 "initialize".
的意思
然后你可以简单地通过
调用初始化
Component.onCompleted: Qml_cpp_interface.getInitDrone()
此外,我没有看到任何从 QML 初始化的正当理由,我的意思是您可以直接从 C++ 初始化,甚至可以从 Qml_cpp_interface
的构造函数中隐式初始化。所以当你的 GUI 加载时,你已经初始化了。
我遇到以下问题:
我写了一个 qml-GUI 和一个接口 class 来通过连接 qml 端的信号和 c++ 端的槽来与一些 C++ 代码通信。基于事件或按钮的触发器工作正常,但我需要一个必须在启动时直接触发的信号。我使用 ApplicationWindow
中的 Component.onCompleted
进行了尝试。然而,
the output "setInitDrone() called" is generated but
getInitDrone()
is never reached. The QT documentation says: "The order of running the onCompleted handlers is undefined."
当我尝试发送信号时,是否可以确保信号已经初始化,或者有没有其他方法可以代替 Component.onCompleted?
谢谢你的帮助!
main.qml:
ApplicationWindow{
id: appWindow
visible: true
minimumHeight: 800
minimumWidth: 700
visibility: Window.Maximized
signal setInitDrone()
Component.onCompleted: {
setInitDrone()
print("setInitDrone() called")
}
}
qml_cpp_interface.cpp:
void Qml_cpp_interface::getInitDrone(){
qDebug() << "Cpp initDrone received";
flightserver.init();
}
groundstation.cpp:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
//Connect with C++ code
QObject *item = engine.rootObjects().first();
Qml_cpp_interface qml_cpp_interface;
QObject::connect(item, SIGNAL(setInitDrone()), &qml_cpp_interface,SLOT(getInitDrone()));
return app.exec();
你做错了,你应该从 QML 访问 C++,而不是从 C++ 访问 QML。
向 QML 公开 Qml_cpp_interface
,因为公开核心逻辑接口是有意义的。由于您正在进行初始化,因此您甚至不需要信号,因为据推测,您只需要初始化一次,这就是 "initialize".
然后你可以简单地通过
调用初始化Component.onCompleted: Qml_cpp_interface.getInitDrone()
此外,我没有看到任何从 QML 初始化的正当理由,我的意思是您可以直接从 C++ 初始化,甚至可以从 Qml_cpp_interface
的构造函数中隐式初始化。所以当你的 GUI 加载时,你已经初始化了。