QML:动态地将矩形添加到组件实例的子级

QML:动态地将矩形添加到组件实例的子级,qml,Qml,我有一个要动态添加内容的组件: MyThing.qml: Item{ Rectangle { id: r1 } } main.qml MyThing { id: c1 } 在main.qml中的下一行代码中,我如何动态地将子矩形添加到c1中的r1?首先,您必须将r1作为MyThing.qml中根对象的属性公开,以便它在该范围之外可见。您可以使用一个: MyThing.qml: import QtQuick 2.0 Item { prop

我有一个要动态添加内容的组件:

MyThing.qml: 

Item{
    Rectangle {
        id: r1
    }
}

main.qml

MyThing {
    id: c1
}

在main.qml中的下一行代码中,我如何动态地将子矩形添加到c1中的r1?

首先,您必须将
r1
作为
MyThing.qml
中根对象的属性公开,以便它在该范围之外可见。您可以使用一个:

MyThing.qml

import QtQuick 2.0

Item {
    property alias rect: r1

    Rectangle {
        id: r1
        anchors.fill: parent
    }
}
import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 600
    height: 400
    visible: true

    MyThing {
        id: c1
        anchors.fill: parent
        Component.onCompleted: {
            Qt.createQmlObject("
                import QtQuick 2.0

                Rectangle {
                    color: \"salmon\"
                    anchors.fill: parent
                    anchors.margins: 10
                }
            ", rect)
        }
    }
}
然后,可以使用创建子矩形,例如:

main.qml

import QtQuick 2.0

Item {
    property alias rect: r1

    Rectangle {
        id: r1
        anchors.fill: parent
    }
}
import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 600
    height: 400
    visible: true

    MyThing {
        id: c1
        anchors.fill: parent
        Component.onCompleted: {
            Qt.createQmlObject("
                import QtQuick 2.0

                Rectangle {
                    color: \"salmon\"
                    anchors.fill: parent
                    anchors.margins: 10
                }
            ", rect)
        }
    }
}
如果子矩形组件存在于单独的文件中,请使用

对于更结构化的方法,您可能希望使用某种视图,如。视图将负责创建子矩形,您只需控制应该创建多少子矩形(通过属性等)