object->setProperty not working QML C++

  • Hi All

    I am trying to change QML loader visibie property from true to false from c++ code and its not working here is the code attached. please give me some suggestions.


    GameForm {
        Loader {
            id: scene1
            objectName: "scene1"
            visible: true
        Loader {
            id: scene2
            objectName: "scene2"
            visible: false


    QQmlEngine engine;
    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/Game.qml")));
    QObject *object = component.create();
    QObject *scene1 = object->findChild<QObject*>("scene1");
            qDebug() << "Entered here";
            scene1->setProperty("visible", QString("false"));
           //scene1->setProperty("visible", false);

    When i run this "Entered here" is coming. but the visible property not working.

    Note: i tested without passing as string too.

    Thanks for your help.

  • Moderators

    Hi @AmalRaj and Welcome,
    Whenever you create an item using QQmlComponent and create you must set it a visual parent using setParentItem. For that you will need to cast it to QQuickItem otherwise it wont be displayed

    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/Game.qml")));
    QQuickItem *object = qobject_cast<QQuickItem*>(component.create());

    Then try setting its properties.

    P.S: The forum use markdown syntax. So while posting code surround it with ``` (3 backticks) so that it appears more readable. I have edited it this time.

Log in to reply

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