qtqmlqtquick2

How to access delegate properties in ListView using index


I want to access delegate properties in ListView. I've tried with contentItem but sometimes it's undefined.

Here is my code:

ListModel {
    id: modeldata
    ListElement{
        name:"don"
        rank:1
    }
    ListElement{
        name:"shan"
        rank:2
    }
    ListElement{
        name:"james"
        rank:3
    }
    ListElement{
        name:"jeggu"
        rank:4
    }
}

Component {
    id: delegateitem
    Row {
        property int count: rank
        Rectangle{
            width: 100
            height: 50
            Text{
                anchors.centerIn: parent
                text: name
            }
        }
    }
}

ListView {
    id: listview
    focus: true
    anchors.fill: parent
    model: modeldata
    delegate: delegateitem
    onCurrentIndexChanged: {
        console.log("position",currentIndex)
        console.log("property",contentItem.children[currentIndex].count);
    }
}

Problem invalid output at position 1:

qml: position 0
qml: property 1
qml: position 1
qml: property undefined
qml: position 2
qml: property 2
qml: position 3
qml: property 3

Solution

  • First of all: if you are trying to access list elements from outside your list, this is a good indicator that you should rethink your desing.

    Now the solution: a listview has more children than only its items. You can filter them out by defining a property "property string type: "myType" " for example. Then find the items by looping over the children and only take those where the type property equals "myType". Its somewhat of a hack but again you should really not be doing this in the first place.