【问题标题】:How to connect to an attached signal from C++?如何连接到来自 C++ 的附加信号?
【发布时间】:2017-06-21 16:07:30
【问题描述】:

我想从 C++ 连接到对象的 Component.onCompleted 信号。我应该使用什么语法?

【问题讨论】:

  • 你是如何创建组件的?来自 C++ 还是 QML?
  • 我认为这没有意义。例如,当您使用QQmlApplicationEngine::load() 创建 QML 树时,Component.onCompleted 将在您连接到信号之前执行。无论如何 - 您可以为从 Component.onCompleted 调用的对象创建一些代理信号,然后从 C++ 连接到此信号。
  • 通过 setContextProperty() 使 QML 可以访问 slot 对象,并直接从 Component.onCompleted 处理程序调用 slot

标签: qt qml qtquick2 signals-slots qt-signals


【解决方案1】:

一种解决方案是从 QML 调用 C++ 函数:

Component.onCompleted:Qml_utils.connect_qmlobject(this)

C++ 代码

Q_INVOKABLE void qml_utils::connect_qmlobject(QObject*obj) {
  //do something with QML QObject:
  connect(obj, SIGNAL(destroyed(QObject*)),
          this,SLOT(disconnect_qmlobject(QObject*)));
}

【讨论】:

    【解决方案2】:

    因此您可以使用此代码来访问 Component.completed 和 Component.destruction 信号:

    QObject* attached_component = qmlAttachedPropertiesObject<QQmlComponent>(qml_component);
    QObject::connect(attached_component, SIGNAL(destruction()), this, SLOT(onDestruction()));
    QObject::connect(attached_component, SIGNAL(completed()), this, SLOT(onCompleted()));
    

    qml_component 是您的 QML 组件指针,“this”是具有 onDestruction 和 onCompleted 插槽的对象。 也许这是一个 hack,但现在它可以工作了(QT 5.8 VS2013)

    【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多