[Qt-interest] Problem with finding qml elements placed within ListView delegate from C++ code

Дмитрий Шаховский dshakhovski at gmail.com
Thu Jul 7 20:19:08 CEST 2011


Hi,
I have a problem when I tried to find a qml element placed within ListView
delegate from C++ code.

E.g.

Rectangle {
   ...
   ListView{
       ...
       delegate: Rectangle{
                     objectName: "rect"
                 }

       model: ListModel{
                  ListElement{}
                  ListElement{}
                  ListElement{}
              }
   }
}

And somewhere in C++ code

QDeclarativeView *view = new QDeclarativeView;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
QObject* rootObject = view->rootObject();
QObject* obj = rootObject->findChild<QObject*>("rect");

obj will be null.

If in qml I ask Rectangle's ancestor, eg.
...
delegate: Rectangle{
            objectName: "rect"
            Component.onCompleted: { console.log("rect container " +
parent.parent) }
         }
...
output will be QdeclarativeListView + address

If I still be able to get a pointer to Rectangle as QObject*, as follows

Rectangle {
   ...
   signal rectClicked(variant id)

   ListView{
       ...
       objectName: “listView”
               delegate:
                   Item {
                       …
                       MouseArea {
                           onClicked: rectClicked(rect)
                           anchors.fill: parent
                       }
                       Rectangle{
                           id: rect
                           objectName: "rect"
                       }
                   }
       ...
   }
   ...
}

in C++ slot connected to rectClicked signal

void SomeObject::onRectClicked(QVariant element)
{
   QObject* rootObject = declarativeView->rootObject();
   QObject* listView = rootObject->findChild<QObject*>("listView");

   QObject* obj = element.value<QObject*>()->parent()->parent();
   //obj will be null instead of the equality of listView
   //(element.value<QObject*>() is QDeclarativeRectangle)
}

So delegate component children are not in root object's tree.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110707/a2ccf78c/attachment.html 


More information about the Qt-interest-old mailing list