Search code examples
qtcomboboxqmlqtquick2qtquickcontrols2

QtQuick2 ComboBox with sections


I would like to have the same section functionality in a ComboBox like in the ListView (Example of sectioned ListView).

But I cannot find anything like this in the ComboBox.

Is this even possible?


Solution

  • In order to have the same section functionality as a ListView in a ComboBox, you can simply include a ListView in your ComboBox.

    You can customize basically all the Qt Quick Controls 2, here is an example for ComboBox : https://doc.qt.io/qt-5/qtquickcontrols2-customize.html#customizing-combobox

    In your case you need to customize the popup property to include a ListView with sections enabled.

    I wrote an example :

    ComboBox {
        id: control
        width: 200
        model : ["Albert Dupontel","Antoine Griezmann","Peter Sagan","Rodney Mullen","Serena Williams"]
        popup: Popup {
            y: control.height
            width: control.width
            implicitHeight: Math.min(contentItem.implicitHeight, 300)
            padding: 0
    
            contentItem: ListView {
                clip: true
                implicitHeight: contentHeight
                model: control.popup.visible ? control.delegateModel : null
                currentIndex: control.highlightedIndex
                section.property: "modelData"
                section.criteria: ViewSection.FirstCharacter
                section.delegate: Label {
                    x: 10
                    text: section
                }
    
                ScrollIndicator.vertical: ScrollIndicator { }
            }
        }
    }
    

    It renders like that : ComboBox with section