I need to dynamically create a QQuickitem & add to my main.qml.
Trying to do it, I create a QQuickitem in the following way.
qml_engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
// Creating my QQuickItem here
QQuickItem * dynamic_quick_item = new QQuickItem();
dynamic_quick_item->setObjectName("DynamicQuickItemObject");
dynamic_quick_item->setHeight(500);
dynamic_quick_item->setWidth(500);
dynamic_quick_item->setParent(qml_engine->parent());
I have access to QQmlApplicationEngine in main.cpp.
Question: How can I add dynamic_quick_item to items in my main.qml? I want to dynamically add dynamic_quick_item to the list of items in my main.qml from C++ side.
It doesn't necessary be added to main.qml. Only want to add a QQuickItem to the list of QML items defined in my main.qml which can be very much like the other QML items defined in main.qml. Is there a possible way to acheive this?
Update: Doing the following should get a valid instance of the QQuickItem I have added. But it doesnt
QQuickItem *my_dynamic_quickitem = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("DynamicQuickItemObject");
I get my_dynamic_quickitem as null which means that the QQuickItem I created never got added
A QML item can be dynamically loaded with QQmlComponent. QQmlComponent loads a QML document as a C++ object that can then be modified from C++ code.
You can find the detailed description in this guide http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html#loading-qml-objects-from-c
This is the example of dynamic creation a QML object and putting it to the QML file.