Add objects to QML layout from C++

一世执手 提交于 2019-12-13 19:36:13

问题


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()
}

回答1:


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.



来源:https://stackoverflow.com/questions/31890372/add-objects-to-qml-layout-from-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!