Reputation: 302
Consider the following:
Repeater {
model: 10;
delegate: Rectangle {
width: 200; height: 20;
color: "white";
}
}
How can I give all the 10 rectangles a different id
?
Upvotes: 6
Views: 5976
Reputation: 2789
Depending on what you want to do you can either
You can access elements their index, using the itemAt
method of the repeater, as indicated by @eyllanesc. Be careful, as delegates may not be instantiated yet.
Repeater {
id: repeater
model: 5
Component.onCompleted: {
if (repeater.count > 0) {
var firstRect = repeater.itemAt(0)
// do something
}
}
Rectangle { /*...*/ }
}
itemAdded
signalYou can connect to the itemAdded
signal of the Repeater
. This signal is triggered whenever an item is added (of course) and will provide the item index
and item
.
Repeater {
id: repeater
model: 5
property Item firstRect
onItemAdded: {
// `index` and `item` come from the signal
if (index == 0) {
firstRect = item
// Or do something with item
}
}
Rectangle { /*...*/ }
}
You can have rectangles assign themselves to a property declared in one of their parents. This is usually not preferred, as your delegate now depends on that named property to be there, but it might be useful.
Repeater {
id: repeater
model: 5
// That property can be anywhere
property Item firstRect
Rectangle {
id: rect
width: 50; height: 50;
Component.onCompleted: {
// Index is automatically populated by the Repeater
if (index == 0)
repeater.firstRect = rect
}
}
}
Most of the time, you want to avoid any dependency from delegates to parents, so solutions A and B are preferred. But it always depends!
Upvotes: 5
Reputation: 244311
You can not assign a different id, also the id has a scope whose limit is the delegate, if you want to access an item you must use the itemAt()
method passing the index:
Repeater {
id: repeater
model: 10;
delegate: Rectangle {
width: 200;
height: 20;
color: "white";
}
}
// ...
var item = repeater.itemAt(2)
Upvotes: 8