Reputation: 221
I've done a bit of searching but I've failed to find an answer which must be so simple it hasn't warranted a question thus far. Anyway I'm new to QML and struggling to find a way to add items to a Grid dynamically post-creation.
Basically I have a Flickable with a Grid inside it containing (by default) four instances of a custom class named ImageTile, and when the MouseArea detects there's a click it wants to add 2 instances of ImageTile to that grid.
Here is a snippet of the code:
Flickable {
anchors.fill: parent
contentWidth: 400
contentHeight: 800
clip: true
MouseArea {
id: mouseArea
anchors.fill: parent
onclicked: { /* ADD TWO ImageTile TO imageGrid */ }
}
Grid {
id: imageGrid
columns: 2
spacing: 2
Repeater {
model: 4
ImageTile { }
}
}
}
As you can see I'm wondering what I should put inside the onClicked event to achieve adding two new instances of ImageTile to imageGrid.
Thanks in advance for any help!
Upvotes: 4
Views: 2942
Reputation: 221
So thanks to being pushed in the right direction by MrEricSir I've figured the issue out.
First I had to specify a proper Data Model for the Repeater to use, and then assign a delegate function to convert information in the data model to actual QML elements. Appending to the data model automatically triggered the Repeater to execute the delegate function.
Flickable {
anchors.fill: parent
contentWidth: 400
contentHeight: 800
clip: true
ListModel {
id: imageModel
ListElement { _id: "tile0" }
ListElement { _id: "tile1" }
ListElement { _id: "tile2" }
ListElement { _id: "tile3" }
}
MouseArea {
id: mouseArea
anchors.fill: parent
onclicked: {
imageModel.append({ _id: "tile" + imageModel.count })
}
}
Grid {
id: imageGrid
columns: 2
spacing: 2
Repeater {
model: imageModel
delegate: ImageTile { id: _id }
}
}
}
Upvotes: 4