I have an Component that I want to add content to dynamically:
MyThing.qml:
Item{
Rectangle {
id: r1
}
}
main.qml
MyThing {
id: c1
}
In the next line of code in main.qml how would I dynamically add a child rectangle to r1 in c1?
First, you have to expose r1
as a property of the root object in MyThing.qml
, so that it's visible outside of that scope. You can do that using an alias
:
MyThing.qml
:
import QtQuick 2.0
Item {
property alias rect: r1
Rectangle {
id: r1
anchors.fill: parent
}
}
Then, you can use Qt.createQmlObject()
to create the child rectangle, for example:
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)
}
}
}
If the child rectangle component exists in a separate file, use Qt.createComponent()
.
For a more structured approach, you'd want to use some kind of view, like ListView
. The view would take care of creating the child rectangles, and you'd merely control how many should be created (via the model
property, amongst others).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.