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

Adding QML element from C++



  • Hello, I am trying to add QML elements in C++ but it doesn't work.

    I have tried to (1) find a parent, (2) create QQmlComponent, (3) create an object, and (4) setParent.

    1. QObject *parent = engine.rootObjects().first()->findChild<QObject*>("row1");;
    QQmlEngine *engine2 = new QQmlEngine;
    QQmlComponent component(engine, QUrl("qrc:/Abc.qml"), QQmlComponent::PreferSynchronous);
    
    1. QObject *rect = component.create();
    2. rect->setParent(parent);

    I added objectName: "parent" to a QML element and Abc.qml is simple:

    Rectangle {
    	width: 100
    	height: 62
    	color: green
    }
    

    What is wrong?


  • Moderators

    Hi @emppu,

    First, you need to understand the difference between object parent and visual parent (see http://doc.qt.io/qt-5/qtquick-visualcanvas-visualparent.html ).

    Qt Quick components are shown based on their visual parent.

    1. QObject *rect = component.create();
    2. rect->setParent(parent);

    This sets the object parent, not the visual parent.

    Instead, you need to use QQuickItem::setVisualParent() QQuickItem::setParentItem(). [EDIT: Typo]



  • @JKSH Thanks!
    In Qt 5.4, the following sets the visual parent.
    child->setParentItem((QQuickItem*)parent);



  • The follow-up question:
    Is it possbie to specify the index of insertion? Or change the existing order of children?


  • Moderators

    You're welcome!

    @emppu said:

    Is it possbie to specify the index of insertion? Or change the existing order of children?

    Yes. Set the "z" property (similar to "x" and "y").


Log in to reply