I can't access to delegated QML Component in Repeater from C++. Please find codes below. Thanks.
main.cpp
#include <QApplication>
#include <QDebug>
#include <QQuickView>
#include <QQuickItem>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl(QStringLiteral("qrc:/Main.qml")));
view.show();
QQuickItem *object = view.rootObject();
QObject *rectangle = object->findChild<QObject*>("rect1");
if (!rectangle)
qDebug() << "MyError: rectangle was not found";
app.exec();
}
Main.qml
import QtQuick 2.4
Row {
Repeater {
model: 3
Rectangle {
width: 50; height: 50
color: index %2 ? "black" : "white"
objectName: "rect" + index
}
}
}
Console output:
MyError: rectangle was not found
I have implemented own recursive function template 'findChild' function in C++.`
template <class T>
SearchType findChild(QQuickItem* object, const QString& objectName)
{
QList<QQuickItem*> children = object->childItems();
foreach (QQuickItem* item, children)
{
if (QQmlProperty::read(item, "objectName").toString() == objectName)
return item;
T child = findChild<QQuickItem*>(item, objectName);
if (child)
return child;
}
return nullptr;
}
And call it instead a default function.
QQuickItem *object = view.rootObject();
QQuickItem *rectangle = findChild<QQuickItem*>(object, "rect1");
if (rectangle)
{
qDebug() << rectangle;
qDebug() << rectangle->objectName();
}
And get output:
QQuickRectangle(0x2222b40, name="rect1", parent=0x22245b0, geometry=50,0 50x50)
"rect1"