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?
-
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,- Create QQmlComponent object
- Use beginCreate() to create object instead of create()
- Cast created object to QQuickItem
- Set QQuickItem's setParentItem
- Set QQuickItem's properties if any
- 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.