qt - 在 Component.onCompleted 之前初始化 QML 信号

标签 qt qml qt-signals

我有以下问题: 我编写了一个 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/

相关文章:

c++ - 如何正确使用 qt 的信号/插槽系统

qt - 如何从单击的事件中获取调用按钮

c++ - 没有 QAction 的匹配信号,没有 "go to slot"菜单项

c++ - 在 Windows 上部署 QML 应用程序的正确方法

c++ - Windows 10 上 C++/Qt 项目中的 Taglib

c++ - 在非 Qt 应用程序 (C++) 中使用 Qt 的信号

c++ - QT中子UI窗口打开时如何关闭父UI窗口

c++ - 如何接收 QGraphicsView 的滚动条鼠标事件

properties - 如何在更改之前获取先前的属性值? (在 QML 中)