Search code examples
qtqtstylesheetsqcombobox

How to change QComboBox's first item style when there is no selection


I have a QComboBox with no preselected item. When I first open it, the first item has a light blue color. After I move the cursor on the dropdown list, the hovered item gets dark blue, and there is no more light blue colored entry.

Why is the first item light blue, and how can I change its color using QSS?

enter image description here enter image description here

ui->cb1->addItems({"1111", "2222"});
ui->cb1->setEditable(true);
ui->cb1->lineEdit()->setPlaceholderText(tr("Please select"));
ui->cb1->setCurrentIndex(-1);

Solution

  • The partially highlighted item you see is the current index of the popup (a QListView).

    Qt item views have two similar but independent states: current items and selected items (see the table from the Model/View programming documentation).

    The current item (or index) is primarily related to focus and editing, there can only be one current index for a view.

    The selected index indicates a selection that could correspond to one, more, or no indexes.

    Those two aspects are often commonly related: the current index is normally the selected index, or is part of a selection. In reality, the current index can also be outside the selection: this is similar to what happens when you deselect an icon from a group selection.

    When an item view receives focus, and no current index has been explicitly set, it automatically tries to find the first available/selectable index in its model (using moveCursor()), and sets it as its current index, but without selecting it.

    This is exactly what happens in a combo box when the popup is shown: if a valid index is set in the combo, the view will automatically make it the current and selected index, but if the combo index is -1 there is no valid index set, so it sets the first item as its current, without selecting it.

    The color you're seeing is caused by your current style ("fusion"), which chooses to use a semi transparent color for the "focus frame" based on the palette Highlight role. Other styles may not draw anything at all.

    If you want to change that color, you can use style sheets with the item:focus:!selected selector:

    QComboBox QAbstractItemView::item:focus:!selected {
        background-color: orange;
    }
    

    Alternatively, if you want to completely avoid that behavior, just explicitly set the current index to the view to an invalid index right after setting the -1 index:

    ui->cb1->setCurrentIndex(-1);
    ui->cb1->view()->setCurrentIndex(QModelIndex());