S.Lee
S.Lee

Reputation: 1

Individual IDs of Repeater child in QML

I was wondering if it is possible to assign individual IDs to the child of a repeater in QML?

For example, if my repeater was to create 10 rectangles, how do I assign each of them a unique id? e.g. rec1, rec2, etc.

Upvotes: 0

Views: 1939

Answers (2)

Juan Gonzalez Burgos
Juan Gonzalez Burgos

Reputation: 982

Just add this property to any QML object that requires a unique id:

readonly property string uniqueId: `${this}`.substring(`${this}`.indexOf("(0x") + 2).replace(")", "")

Upvotes: 2

folibis
folibis

Reputation: 12874

As already said above id is not a regular property and cannot be set or changed at runtime. You cannot reference this attribute, for example the following code will not work:

console.log(obj.id); 

The nearest analogue of id from C++ is a variable name:

auto id = new Object();

when you can reference the name but cannot set or change it.

As for the issue, you can reference an item using objectName, or by using some specified access function, for example:

Row {
    id:row
    anchors.centerIn: parent
    spacing: 5
    Repeater {
        id: container
        model: 10
        Text {
            text:"item" + index
            objectName: "item" + index
        }
        Component.onCompleted: {
            container.itemAt(5).text = "changed1";
            findChild(row, "item6").text = "changed2";
        }

        function findChild(obj, name) {
            for(var i = 0;i < obj.children.length;i ++){
                if(obj.children[i].objectName === name)
                    return obj.children[i];
            }
            return undefined;
        }
    }
}

Upvotes: 3

Related Questions