user11918575
user11918575

Reputation:

Is there a way to grab the index of an item in Listview?

I am using listview in Qt/qml and am trying to display a screen that gives font A to the first text in the list, then font B to the second, then A, then B and so on...

I've been trying to use a conditional in the the font property to the effect of font:(index % 2) fontA : fontB

I haven't been able to accurately grab the index of each and would appreciate any advice or direction, thank you!

Upvotes: 0

Views: 333

Answers (1)

T3 H40
T3 H40

Reputation: 2436

You can use the index property for this. It will be available in your delegate, no matter whether its a Component or a direct child. Check the following snippet:

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView {
        id: listView
        anchors.fill: parent
        model: 5

        delegate: Rectangle {
            width: listView.width
            height: listView.height / listView.count

            color: index === 1 ? "red" : "blue"
        }
    }
}

index will hold the index of your item, starting at 0. So in this example, the second item will be colored red.

The same works for components:

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView {
        id: listView
        anchors.fill: parent
        model: 5

        delegate: comp
        
        Component {
            id: comp
            
            Rectangle {
                width: listView.width
                height: listView.height / listView.count
    
                color: index === 1 ? "red" : "blue"
            }
        }
    }
}

Upvotes: 2

Related Questions