QQmlComponent creation fails to set proper parent



  • I am creating QML components from C++, and while creation succeeds, the created item remains invisible since its parent is not properly set:

    @QQmlComponent c(engine, path + name + ".qml", canvas);
    ui = qobject_cast<UI *>(c.create());@

    Canvas is indeed a valid QML Item:

    @qDebug() << canvas;@

    outputs

    @QQuickItem (this = 0x1692f500 , name= "canvas" , parent = 0x168882b8 , geometry = QRectF(0,0 500x500) , z = 0 )@

    but

    @Component.onCompleted: console.log("created " + parent)@

    outputs

    @created null@

    Any ideas why that might be happening? A valid parent item is passed to the constructor, yet the item is created without a parent?


  • Moderators

    Hi,

    AFAIK, you should use "setParentItem":http://qt-project.org/doc/qt-5/qquickitem.html#parent-prop to set parent for the QQuickItem that you create and not to the component.

    Also Component.onCompleted is called as soon as you create the component using create().
    Instead use "beginCreate":http://qt-project.org/doc/qt-5/qqmlcomponent.html#beginCreate and then set properties what ever you wish to and at the end call "completeCreate":http://qt-project.org/doc/qt-5/qqmlcomponent.html#completeCreate. This will ensure that parentItem has been set to the Item before the Component is Completed.
    So to sum up,

    1. Create QQmlComponent object
    2. Use beginCreate() to create object instead of create()
    3. Cast created object to QQuickItem
    4. Set QQuickItem's setParentItem
    5. Set QQuickItem's properties if any
    6. Call completeCreate()

    Hope this helps...



  • Right. There are two different parenting concepts at play here: the first is the QObject (ownership) parent; the second is the QtQuick (scene / item) parent. Use setParentItem() to bring the item into the scene (by setting the item parent) and therefore make it visible.


Log in to reply
 

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