Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[solved] QObject::findChild() not working for QML Items inside Window



  • Hello,

    I need to get a pointer to one of my QML elements from my C++ code, which should be possible with findChild() (see http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html)

    However, it just doesn't work. When I get the top-level item from window->contentItem() and call findChild(), it keeps returning zero pointer.

    My main.cpp:

    #include <QGuiApplication>
    #include <QQuickWindow>
    #include <QQuickItem>
    #include <QtQml>
    #include <QTimer>
    #include <QtDebug>
    
    void checkItem(QQmlApplicationEngine *pEngine);
    
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
        QTimer::singleShot(2000, [&]() {
            checkItem(&engine);
        });
    
        return app.exec();
    }
    
    void checkItem(QQmlApplicationEngine *pEngine) {
        QQuickWindow *window = qobject_cast<QQuickWindow *>(pEngine->rootObjects().first());
        QQuickItem *topItem = window->contentItem();
        qDebug() << "topItem: " << topItem;
    
        QQuickItem *rect = topItem->findChild<QQuickItem *>("myItem");
        qDebug() << "rect: " << rect;
    }
    

    My main.qml:

    import QtQuick 2.5
    import QtQuick.Window 2.2
    
    Window {
        visible: true
    
        Rectangle {
            width: 100
            height: 100
            color: "lightblue"
            objectName: "myItem"
    
            Text {
                text: qsTr("Hello world!")
                anchors.centerIn: parent
            }
        }
    }
    

    Output of the program:

    topItem:  QQuickRootItem(0x1e929b0, parent=0x0, geometry=0,0 160x160)
    rect:  QQuickItem(0)
    

    Of course I also tested whether topItem isn't the rectangle itself, but topItem->objectName() prints just empty string.
    Any ideas?



  • I got it working by not searching among children of topItem, but of window:

    QQuickItem *rect = window->findChild<QQuickItem *>("myItem");
    

    I find it astonishing, because window->contentItem() should return the root item of the scene. So my light blue rectangle should definitely be one of its children.


Log in to reply