Search code examples
qtcomboboxqml

Customize a ComboBox in QML


I'm trying to customize the ComboBox for a custom application but I'm unable to figure out where I would need to make my changes so as to affect the color and radius of the 'highlight' rectangle. I have referred to this link for customizing the component so far. However, I couldn't find anything in this code that corresponds to the rectangle that highlights the currently selected/hovered option in the ComboBox popup.

My ComboBox component has mostly the same code as in the example above, but here it is below:

import QtQuick 2.12
import QtQuick.Controls 2.12

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

    delegate: ItemDelegate {
        width: control.width
        contentItem: Text {
            text: modelData
            color: "#21be2b"
            font: control.font
            elide: Text.ElideRight
            verticalAlignment: Text.AlignVCenter
        }
        highlighted: control.highlightedIndex === index
    }

    contentItem: Text {
        leftPadding: 0
        rightPadding: control.indicator.width + control.spacing

        text: control.displayText
        font: control.font
        color: control.pressed ? "#17a81a" : "#21be2b"
        verticalAlignment: Text.AlignVCenter
        elide: Text.ElideRight
    }

    background: Rectangle {
        implicitWidth: 120
        implicitHeight: 40
        border.color: control.pressed ? "#17a81a" : "#21be2b"
        border.width: control.visualFocus ? 2 : 1
        radius: 12
    }

    popup: Popup {
        y: control.height - 1
        width: control.width
        implicitHeight: contentItem.implicitHeight
        padding: 1

        contentItem: ListView {
            clip: true
            implicitHeight: contentHeight
            model: control.popup.visible ? control.delegateModel : null
            currentIndex: control.highlightedIndex

            ScrollIndicator.vertical: ScrollIndicator { }
        }

        background: Rectangle {
            border.color: "#21be2b"
            radius: 12
        }
    }
}

Solution

  • In order to set a radius on the highlight you need to customize the background property of the ItemDelegate like so:

    ItemDelegate {
        id: itemDelegate
        contentItem: Text {
            text: modelData
            color: "#21be2b"
            font: control.font
            elide: Text.ElideRight
            verticalAlignment: Text.AlignVCenter
        }
        highlighted: control.highlightedIndex === index
    
        background: Rectangle {
            width: control.width
            radius: 12
            color: itemDelegate.highlighted ? "blue" : "red"
        }
    }