简体   繁体   English

QML和C ++:如何将对导出的C ++对象的引用传递给导出的C ++类?

[英]QML and C++ : How to pass a reference of an exported C++ object to an exported C++ class?

I exported a C++ class and object like so: 我导出了一个C++类和对象,如下所示:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/QQuickViewExample/main.qml"));
    viewer.showExpanded();

    //object export
    ClassA classA(QString stuff);
    QQmlContext* context = viewer.engine()->rootContext();
    context->setContextProperty("_classA", &classA);

    //class export
    qmlRegisterType<ClassB>("CustomComponents", 1, 0, "ClassB");


    return app.exec();
}

I will create an arbitrary number of QML objects with ClassB embedded inside. 我将创建任意数量的QML对象,并在其中嵌入ClassB I want every ClassB to have a reference or pointer to the 1 ClassA that exists in this program. 我希望每个ClassB都具有对该程序中存在的1个ClassA的引用或指针。 How can I, in QML , grab a reference of ClassA when I am initializing ClassB in my QML objects, so that ClassB can use ClassA ? QML对象中初始化ClassB时,如何在QML中获取ClassA的引用,以便ClassB可以使用ClassA

You have to change the order of actions: 您必须更改操作顺序:

  1. register B 寄存器B
  2. set A instance on the root context 在根上下文上设置一个实例
  3. load the source, where you instantiate (as many times as you need): 在实例化的地方加载源(根据需要多次):

    B { aPtr: _classA }

The rationale is: 理由是:

  • for smth to appear in QML sources and be used to instantiate classes, those classes have to be registered first (a C++ QML plugin could do that too) 为了使smth出现在QML源代码中并用于实例化类,必须首先注册这些类(C ++ QML插件也可以这样做)
  • if items are relying on existence of a context property, they should be created only after the context property has been set 如果项目依赖于上下文属性的存在,则应仅在设置上下文属性后才创建它们

Given that, steps (1) and (2) above can actually be swapped. 鉴于此,实际上可以交换上面的步骤(1)和(2)。

There are ways to create, parent and wire everything by hand from C++, I believe, but that would be an example of extremely dark art (think creating bindings manually from JS expressions, creating a context, then instantiating items into it...); 我相信,有很多方法可以通过C ++手动创建,父代和连接所有东西,但是那将是极其黑暗的艺术的一个例子(考虑从JS表达式手动创建绑定,创建上下文,然后实例化其中的项目...) ; never seen that in the wild :) 从来没有在野外见过:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM