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,

  • I have the same problem now. Does anyone has a solution for it?

  • Moderators

    @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 using setParentItem
      (See it here and here)
    • Setting x and y properties after item creation. x and y 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());

  • The second point seems to be a good workaround.

Log in to reply

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