我有以下问题:
我编写了一个 qml-GUI 和一个接口(interface)类,通过将 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();
}
地面站.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_cpp_interface
到 QML,因为公开核心逻辑接口(interface)是有意义的。由于您正在进行初始化,因此您甚至不需要信号,因为大概您只会初始化一次,这就是“初始化”的含义。
然后你可以简单地通过调用初始化
Component.onCompleted: Qml_cpp_interface.getInitDrone()
此外,我没有看到任何从 QML 初始化的有效理由,我的意思是您可以直接从 C++ 初始化,甚至隐式从 Qml_cpp_interface
初始化。的构造函数。因此,当您的 GUI 加载时,您就已经初始化了。
关于qt - 在 Component.onCompleted 之前初始化 QML 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893542/