[英]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: 您必须更改操作顺序:
load the source, where you instantiate (as many times as you need): 在实例化的地方加载源(根据需要多次):
B { aPtr: _classA }
The rationale is: 理由是:
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.