[英]How To Pass Component Pointer From QML To C++?
What is the easiest way to pass a component pointer created in a QML file to C++?将在 QML 文件中创建的组件指针传递给 C++ 的最简单方法是什么? From Qt Documentation explanations we could take the QML file root object and then search for our component
objectName
.从Qt 文档解释我们可以获取 QML 文件根目录 object 然后搜索我们的组件
objectName
。 But it's hard to keep sync the components objectName
in both C++ codes and QML codes:但是很难在 C++ 代码和 QML 代码中保持组件
objectName
同步:
Just for Copy/Paste: qml_pass_objectName_example仅用于复制/粘贴: qml_pass_objectName_example
auto const root = engine.rootObjects();
if(!root.empty())
{
auto const obj = root.first()->findChild<test_item*>("testItem");
if(obj)
{
c.setup_test(obj);
}
else
{
qDebug() << "Couldn't Cast";
}
}
else
{
qDebug() << "Empty";
}
I tried to pass the component from QML code on Component.onCompleted
:我试图通过 Component.onCompleted 上的 QML 代码传递
Component.onCompleted
:
TestItem
{
id: testItemId;
Component.onCompleted: controller.setup_test(testItemId);
}
class controller : public QObject
{
Q_OBJECT
public slots:
Q_INVOKABLE void setup_test(test_item* item)
{
item->f();
}
};
#include "main.moc"
int main(int argc, char* argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
controller c;
qmlRegisterType<test_item>("qml.pass.id", 1, 0, "TestItem");
engine.rootContext()->setContextProperty("controller", &c);
engine.load("qrc:/qml_pass_id_example/main.qml");
return app.exec();
}
And I think this is much simpler than using objectName
, but I couldn't find any related documentation about passing the component's ID to C++ functions.而且我认为这比使用
objectName
简单得多,但是我找不到任何关于将组件的 ID 传递给 C++ 函数的相关文档。 So my questions:所以我的问题:
The easy thing is debatable since it depends on the definition of what is easy or difficult for each case so I will not answer this question since it falls outside of SO.容易的事情是有争议的,因为它取决于每种情况下容易或困难的定义,所以我不会回答这个问题,因为它不属于 SO。
Yes, it is valid to export any QML object to C ++.是的,导出任何 QML object 到 C ++ 都是有效的。 The id is the reference to the object so you are not passing the name "testItemId" but you are passing a
test_item
object that has as identifier "testItemId". id 是对 object 的引用,因此您没有传递名称“testItemId”,而是传递了一个具有标识符“testItemId”的
test_item
object。
Note: It is recommended not to expose any QML object to C ++ (or do it for a minimum time) since its life cycle is managed by QML so it could be eliminated at any moment causing you to access pointers that no longer have associated objects.注意:建议不要暴露任何 QML object 到 C ++(或暴露最短时间),因为它的生命周期由 QML 管理,因此它可能随时被淘汰,导致您访问不再关联的指针对象。 .
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.