Access anchors.centerIn programatically
-
Hello Folks;
I'm trying to do the following in a C++ class in which I programmatically create QQuickItems:
@
QQmlComponent vertexComponent(_engine, "../Resources/qml/MyItem.qml");
QObject *vObject = vertexComponent.create();
QQuickItem vQI = qobject_cast<QQuickItem>(vObject);
vQI->setProperty("anchors.centerIn", "parent");
...
@However, I'm finding that I'm unable to set the anchors.centerIn property in this manner. In fact, I can find no way to access and set the anchors value through QQuickItem or the QMetaObject, as they seem to be private.
Might anyone know how I might be able to set anchors values from C++?
Thank you very much,
S.T. -
I have the same problem now. Does anyone has a solution for it?
-
@PhTe I too had a similar requirement and ended up doing one of the following 2 ways
- Setting the
anchors.centerIn: parent
in the QML to be loaded itself. Make sure parent is set usingsetParentItem
(See it here and here) - Setting
x
andy
properties after item creation.x
andy
can be calculated using its width and height according to parent's width and height.
QQuickItem *parent = view.rootObject(); //get parent item QQmlComponent component(view.engine(),QUrl("qrc:/child.qml")); //load child item QQuickItem *child = qobject_cast<QQuickItem*>(component.create()); child->setParentItem(parent); child->setProperty("x",parent->width()/2-child->width()/2); child->setProperty("y",parent->height()/2-child->height()/2);
- Setting the
-
The second point seems to be a good workaround.