5
votes

If wrote the following code:

Repeater { model: 10; 
delegate: Rectangle { width: 200; height:           
20; color: "white";}}

How can I give all the 10 rectangles a different id?

2

2 Answers

8
votes

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)
4
votes

Depending on what you want to do you can either

A. Access the item from its index

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 { /*...*/ }
   }

B. Use itemAdded signal

You 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 { /*...*/ }
    }

C. Delegate assign itself to a property

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!