0

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

TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159

1 Answers1

0

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.

#include <QGuiApplication>
#include <QQmlComponent>
#include <QQmlEngine>
#include <QQuickItem>
#include <QQuickView>

int main(int argc, char** argv)
{
    QGuiApplication app(argc, argv);

    // Init the view and load the QML file.
    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QUrl("qrc:///closeups/closeups.qml"));

    // The size of the window
    view.setMinimumSize(QSize(800, 600));

    // Create Text QML item.
    QQmlEngine* engine = view.engine();
    QQmlComponent component(engine);
    component.setData("import QtQuick 2.0\nText {}", QUrl());
    QQuickItem* childItem = qobject_cast<QQuickItem*>(component.create());

    if (childItem == nullptr)
    {
        qCritical() << component.errorString();
        return 0;
    }

    // Set the text of the QML item. It's possible to set all the properties
    // with this way.
    childItem->setProperty("text", "Hello dynamic object");
    // Put it into the root QML item
    childItem->setParentItem(view.rootObject());

    // Display the window
    view.show();
    return app.exec();
}