QML findChild ListModel not found when instantiated in Window



  • Hi,

    I just discovered that when you instantiate a ListModel inside Window you can not find it via findChild from the root object. If you put it inside something else it can be found.

    Example code:

    main.cpp:

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    int main(int argc, char *argv[])
    {
        QGuiApplication app(argc, argv);
    
        QQmlApplicationEngine engine;
        engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    
        QList<QObject *> roots = engine.rootObjects();
        if (roots.count() < 1)
            qFatal("Error: No root QML Object found, closing Application");
    
        qDebug("root count: %i", roots.count());
    
        QObject *model = roots[0]->findChild<QObject*>("myModel");
        if (!model)
            qCritical("myModel not found");
    
        return app.exec();
    }
    

    main.qml:

    import QtQuick 2.3
    import QtQuick.Window 2.2
    
    Window {
        id: window
        visible: true
        width: 640
        height: 480
    
        ListModel {
            id: myModel
            objectName: "myModel"
            ListElement {
                name: "first"
            }
            ListElement {
                name: "second"
            }
        }
    
        Column {
            anchors.fill: parent
            Repeater {
                model: myModel
                delegate: Rectangle {
                    width: window.width
                    height: 15
                    color: "blue"
    
                    Text {
                        id: text
                        anchors.fill: parent
                        text: name
                    }
                }
            }
        }
    }
    

    With this code myModel is not found, but when I move it into e.g. Column findChild() finds it.

    Is this a bug?



  • Is this a bug?

    Yes, I think this could be fairly well considered as a bug. It should be easy to fix by setting QQuickWindow as a QObject-parent of QQuickRootItem in http://code.qt.io/cgit/qt/qtdeclarative.git/tree/src/quick/items/qquickwindow.cpp#n520. Not 100% sure if it has any undesired side-effects, though.



  • Solution: Filed this as a bugreport here: https://bugreports.qt.io/browse/QTBUG-55592


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.