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.
QObject *parent = engine.rootObjects().first()->findChild<QObject*>("row1");;
QQmlEngine *engine2 = new QQmlEngine; QQmlComponent component(engine, QUrl("qrc:/Abc.qml"), QQmlComponent::PreferSynchronous);
QObject *rect = component.create();
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?
-
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.
QObject *parent = engine.rootObjects().first()->findChild<QObject*>("row1");;
QQmlEngine *engine2 = new QQmlEngine; QQmlComponent component(engine, QUrl("qrc:/Abc.qml"), QQmlComponent::PreferSynchronous);
QObject *rect = component.create();
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?
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.
QObject *rect = component.create();
rect->setParent(parent);
This sets the object parent, not the visual parent.
Instead, you need to use
QQuickItem::setVisualParent()QQuickItem::setParentItem(). [EDIT: Typo] -
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.
QObject *rect = component.create();
rect->setParent(parent);
This sets the object parent, not the visual parent.
Instead, you need to use
QQuickItem::setVisualParent()QQuickItem::setParentItem(). [EDIT: Typo] -
The follow-up question:
Is it possbie to specify the index of insertion? Or change the existing order of children?