[英]How to invoke method of QML object from C++
I have following QML code: 我有以下QML代码:
Rectangle {
id: mainRect
...
Rectangle{
id: listRect
...
ListModel {
id: idModel
... some stuff added
}
}
}
And I want to clear idModel, using clear method of ListModel. 我想使用ListModel的clear方法清除idModel。 Stuff like this (inside QML) works perfectly:
这样的东西(在QML内部)可以完美地工作:
idModel.clear()
But I want to achieve same in C++. 但是我想在C ++中实现相同的目标。 Tried following:
尝试以下:
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
QQuickItem* item = view.rootObject();
QObject* model = item->findChild<QObject*>("mainRect")->findChild<QObject*>("listRect")->findChild<QObject*>("idModel");
QMetaObject::invokeMethod(model,"clear");
also tried to search model as 还尝试搜索模型为
QObject* model = item->findChild<QObject*>("idModel");
QObject* model = item->findChild<QObject*>("listRect")->findChild<QObject*>("idModel");
But this stuff above not working... I can't even understand - if nothing is found by findChild method in C++, or InvokeMethod is not working. 但这上面的东西不起作用...我什至无法理解-如果C ++中的findChild方法未找到任何内容,或者InvokeMethod不起作用。
Could anyone explain this to me? 有人可以向我解释吗? Using QT5.4 \\ QtQuick 2.4
使用QT5.4 \\ QtQuick 2.4
To use findChild()
you should set objectName
to your qml item. 要使用
findChild()
你应该设置objectName
到您的QML项目。
Rectangle {
id: mainRect
...
Rectangle{
id: listRect
...
ListModel {
id: idModel
objectName: "idModel"
... some stuff added
}
}
}
Then, you can get pointer to your ListModel 然后,您可以获取指向ListModel的指针
QObject* model = item->findChild<QObject*>("idModel");
To invoke method, you should use QMetaObject::invokeMethod()
要调用方法,您应该使用
QMetaObject::invokeMethod()
QMetaObject::invokeMethod(model,"clear");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.