Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Identify first element of a section in a list view



  • Hello!
    Is it possible to determine if a list item element is the first item of a section? I tried using the index, but the index refers to the whole list view?

    Thanks



  • hi,
    @rramos said in Identify first element of a section in a list view:

    Is it possible to determine if a list item element is the first item of a section?

    ListView.previousSection !== ListView.section
    

    complete exeample

        Rectangle {
            id: container
            width: 300
            height: 360
    
            ListModel {
                id: animalsModel
                ListElement { name: "Ant"; size: "Tiny" }
                ListElement { name: "Flea"; size: "Tiny" }
                ListElement { name: "Parrot"; size: "Small" }
                ListElement { name: "Guinea pig"; size: "Small" }
                ListElement { name: "Rat"; size: "Small" }
                ListElement { name: "Butterfly"; size: "Small" }
                ListElement { name: "Dog"; size: "Medium" }
                ListElement { name: "Cat"; size: "Medium" }
                ListElement { name: "Pony"; size: "Medium" }
                ListElement { name: "Koala"; size: "Medium" }
                ListElement { name: "Horse"; size: "Large" }
                ListElement { name: "Tiger"; size: "Large" }
                ListElement { name: "Giraffe"; size: "Large" }
                ListElement { name: "Elephant"; size: "Huge" }
                ListElement { name: "Whale"; size: "Huge" }
            }
    
            // The delegate for each section header
            Component {
                id: sectionHeading
                Rectangle {
                    width: container.width
                    height: childrenRect.height
                    color: "lightsteelblue"
    
                    Text {
                        text: section
                        font.bold: true
                        font.pixelSize: 20
                    }
                }
            }
    
            ListView {
                id: view
                anchors.top: parent.top
                height: container.height
                width: parent.width
                model: animalsModel
                delegate: Text {
                    text: name
                    font.pixelSize: 18
                    color: ListView.previousSection !== ListView.section ? "red" : "blue"
                }
    
                section.property: "size"
                section.criteria: ViewSection.FullString
                section.delegate: sectionHeading
            }
        }
    

Log in to reply