iPherian
iPherian

Reputation: 958

Add objects to QML layout from C++

How can I, from the C++, add some more Rectangles dynamically to the one with id root? For example, two more Rectangles colored red and green?

main.qml:

Rectangle {
    id: root
}

Typical QML objects to add under 'root':

Rectangle { color: "red"; width: 200; height: 200 }
Rectangle { color: "green"; width: 200; height: 200 }

Qt Creator generated main.cpp:

int main(int argc, char *argv[]) { 
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/gui/main.qml"));
    viewer.showExpanded();    
    return app.exec()
}

Upvotes: 2

Views: 4073

Answers (1)

folibis
folibis

Reputation: 12864

The best way to create dynamic items is QML itself. But if you still want to do that in C++ it's also possible. For example:

main.cpp:

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQuickView view;
    view.setSource(QUrl("qrc:/main.qml"));
    view.show();
    QObject *root = view.rootObject();
    QQuickItem * myRect = root->findChild<QQuickItem *>("myRect");
    if(myRect) {
        QQmlComponent rect1(view.engine(),myRect);
        rect1.setData("import QtQuick 2.4; Rectangle { width:100; height: 100; color: \"orange\"; anchors.centerIn:parent; }",view.source());
        QQuickItem *rect1Instance = qobject_cast<QQuickItem *>(rect1.create());
        view.engine()->setObjectOwnership(rect1Instance,QQmlEngine::JavaScriptOwnership);
        if(rect1Instance)
            rect1Instance->setParentItem(myRect);
    }
    return app.exec();
}

main.qml

import QtQuick 2.4

Item {
    width: 600
    height: 600

    Rectangle {
        objectName: "myRect"
        width: 200
        height: 200
        anchors.centerIn: parent
        color:  "green"
    }
}

Since all QML items have corresponding С++ classes it's possible to create QQuickRectangle directly but the header is private and that isn't recommended way.

Also, pay attention, I used objectName to access item from C++, not the id since it is not visible from C++ side.

Upvotes: 5

Related Questions