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

findChild() always returns 0 for QML objects



  • Hi,

    I've got a QML component embedded in a Qt C++ app via QQuickView. Everything loads nice and neat, but now I need to control the QML module by modifying its properties. I've tried a bunch of findChild<QObject *>(''tag''), but I always get null. I've got objectName: ''tag'' set in the QML component, so I assume the tag is set properly. Current code:

    form.cpp:

    QObject *obj = this->findChild<QObject *>("tag");
    if (obj) {
        obj->setProperty("ticks", tick_count);
    } else {
        qDebug() << "Could not find QML component!";
    }
    

    component.qml:

    Item {
        id: tag
        objectName: "tag"
        property int ticks: 0
        /* … */
    }
    

  • Moderators

    @Erlend-E.-Aasland said in findChild() always returns 0 for QML objects:

    this->findChild<QObject *>("tag");

    What is the this object? Is it the QML engine or something that actually holds your QML components?

    objectName: "tag"

    That'c correct. findChild<>() looks for named objects.

    component.qml:

    Are you sure that component is instantiated? Is there only one copy of it?

    In general, I'd rather recommend a different approach. Instead of forcing properties like this, use the Connections element. Add some QObject "controller" which will manage C++ - QML communiacation, add it as engine context property, then refer to it in your QML code. Either like this or like this.



  • @sierdzio Thanks for your input! The this-object was the parent widget holding the QQuickView. I solved it by saving the root object of the QQuickView:

    QObject *obj = quickview->rootObject();
    if (obj)
        obj->setProperty("ticks", tick_count);
    else
        qDebug() << "Could not set tick count!";
    

    Anyway, I'll have a look at the different approach you suggest. It sound like a more robust way of interacting with QML.

    Best regards, E