findChild always returns NULL looking for QML objects
-
Re: [solved] QObject::findChild() not working for QML Items inside Window
I have a QQuickWindow, created a QQmlComponent and setParentItem(window->contentItem)
I'm trying to find one of the QQuickItem's now existing in that window, but
window->findChild<QQuickItem*> returns nothingneither does
window->contentItem->findChildWhat gives? I'm trying to find it by its objectName... this should work, no?
-
Ok, here's the screwy behavior i found
QQmlEngine engine; QQmlComponent formWindowComp(&engine, QUrl("qrc:/formWindow.qml")); QQuickWindow *formWindow=qobject_cast<QQuickWindow*>(formWindowComp.create()); QQmlComponent menuComp(engine, QUrl("qrc:/testqml.qml")); QQuickItem *menu=qobject_cast<QQuickItem*>(menuComp.create()); menu->setParentItem(formWindow->contentItem());
all works find here... i get testqml.qml showing up in my formwindow.qml.
Now when i want to find an element inside of testqml.qml, you'd think i could do
QObject *thing=formWindow->findChild<QObject*>("thing");
but this always returns NULL
This is what works tho...
QObject *thing; auto list=formWindow->contentItem->childItems(); for (auto i : list) { thing=i->findChild<QObject*>("thing"); if (thing) break; }
So why doesn't "thing" exist as a child of formWindow? or why doesn't it exist as a child of formwindow->contentItem?
Why do i have to get the children of contentItem before i can successfully search?
-
parent and parentItem are different concepts parentItem defines the "visual" parent and parent defines the QObject parent.
To get the visual childs you should use childItems.
Take a look at this link
http://doc.qt.io/qt-5/qtquick-visualcanvas-visualparent.html