[英]QML: dynamically add Rectangle to a child of a component instance
我有一個要動態添加內容的組件:
MyThing.qml:
Item{
Rectangle {
id: r1
}
}
main.qml
MyThing {
id: c1
}
在main.qml中的下一行代碼中,如何在c1中向r1動態添加子矩形?
首先,您必須在MyThing.qml
r1
公開為根對象的MyThing.qml
,以使其在該范圍之外可見。 您可以使用alias
來做到這一點:
MyThing.qml
:
import QtQuick 2.0
Item {
property alias rect: r1
Rectangle {
id: r1
anchors.fill: parent
}
}
然后,可以使用Qt.createQmlObject()
創建子矩形,例如:
main.qml
:
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)
}
}
}
如果子矩形組件存在於單獨的文件中,請使用Qt.createComponent()
。
對於更結構化的方法,您需要使用某種視圖,例如ListView
。 該視圖將負責創建子矩形,而您只需要控制應創建的子矩形(通過model
屬性,等等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.