qtcomboboxqmlqtquick2

How to customize ComBox Popup items


I am trying to customize the QML 2.14 ComboBox, and I did follow Customizing ComboBox documentation, but I am not able to customize the ComboBox -> Popup -> ListView -> "delegate".

I want to have a different text color for the list item displayed inside the ComboBox Popup.

ComboBox {
   id: myComboBox
   model: ["First", "Second", "Third"]

   popup: Popup {
      y: myComboBox.height - 1
      width: parent.width
      implicitHeight: contentItem.implicitHeight
 
      contentItem: ListView {
          clip: true
          anchors.fill: parent
          model: myComboBox.popup.visible ? myComboBox.delegateModel : null
          ScrollIndicator.vertical: ScrollIndicator {}

          delegate: Text {
              width: parent.width
              height: 30
              text: "Test" // How to access flat model, modelData is null and model.get(index) is not allowed in .ui.qml  
              color: "#ffffff"
              anchors.horizontalCenter: parent.horizontalCenter
              anchors.left: parent.left
          }

          highlight: Rectangle { color: "yellow" } 
      }
   }
}

But I always see some default list with black text, in the combobox popup.

I'm also not able to apply the highlight to the selected line in the popup.


Solution

  • The Combobox's model is a DelegateModel. That means the delegate is attached to the model. So trying to set the ListView's delegate will not have any effect. But the Combobox has its own delegate property that you can set.

    ComboBox {
        delegate: Text {
            width: parent.width
            height: 30
            text: modelData
            color: "#ffffff"
            anchors.horizontalCenter: parent.horizontalCenter
        }
    }