qtqml

Find position of delegate in QML


I have an QML GridView that is displaying items from a model. A separate overlay needs to know the screen positions of the items within that GridView. However, I am having trouble accessing the positions.

As a minimal example, I tried:

GridLayout {
    columns: 2

    Repeater {
        model: inputs

        Text { text: title }

        onItemAdded: function (idx, item) {
            let pos = item.mapToGlobal(item.x, item.y);
            console.log("Position:", pos, "X: ", item.x, "Y: ", item.y);
        }
    }
}

However, while this puts all five items on the screen, onItemAdded reports the exact same position for each item.

qml: Position: QPointF(458, 262) X:  0 Y:  0
qml: Position: QPointF(458, 262) X:  0 Y:  0
qml: Position: QPointF(458, 262) X:  0 Y:  0
qml: Position: QPointF(458, 262) X:  0 Y:  0
qml: Position: QPointF(458, 262) X:  0 Y:  0

How do I get the individual positions of each item?


Solution

  • You probably call it a little early. The layout is still incomplete.
    You maybe can change it to something like this:

        GridLayout {
            columns: 2
            anchors.fill: parent
    
            Repeater {
                id: repeater
                model: ["apples", "oranges", "pears", "bananas"]
    
                Text { text: modelData }
    
                Component.onCompleted: {
                    for(var i = 0;i < repeater.count;i ++)
                    {
                        let item = repeater.itemAt(i);
                        let pos = item.mapToGlobal(item.x, item.y);
                        console.log("Position:", pos, "X: ", item.x, "Y: ", item.y);
                    }
                }
            }
        }