Search code examples
c++qtcomboboxqtstylesheets

How apply different stylesheet to a QComboBox and its placeholder?


I want to distinguish the placeholder text of a QComboBox using QStyleSheet by drawing the placeholder with a different color.

With Qt6, it's easy to set the placeholder text to a combo box from code if the combo box is editable:

if(someCondition)
    myComboBox->lineEdit()->setPlaceholder("Some placeholder");
else
    myComboBox->lineEdit()->setPlaceholder("Some other placeholder");

So far so good, but if I use a custom stylesheet, so the default grayish placeholder is gone, and it is drawn with the color property. I tried to filter by some property based on this question, but I was not successful.

This is the relevant part of the dark-theme stylesheet:

auto styleSheet = "QWidget {color: white; background-color: #505050}"
                  "QComboBox[text=\"\"] { color: #808080 }";
myComboBox->setStyleSheet(styleSheet);

Currently, this is the result, with white letters:

And this is the expected with a sightly gray color:

Also, I tried to filter to the QComboBox, to the QComboBox[currentText=\"\"] but no success.


Solution

  • To draw the placeholder with darker pen, you have to modify the stylesheet and set to the lineEdit of the QComboBox.

    auto styleSheet = "QWidget {color: white; background-color: #505050}"
                      "QLineEdit[text=\"\"] { color: #808080 }";
    myComboBox->setStyleSheet(styleSheet);
    myComboBox->lineEdit()->setStyleSheet(styleSheet);
    

    QComboBox has no option to handle the placeholder text, because that text is handled by the line edit it has. Therefore, to alter the look and feel of the placeholder, you must use it's QLineEdit. Note, that several properties not make any effect on the line edit, like the background-color or border to say some, because those are handled by the QComboBox.

    Also, if it's not automatically updated, you need to connect the change of the text with the stylesheet update. In the owning widget, connect the text change signal to the update:

    connect(ui->myComboBox->lineEdit(), &QLineEdit::textChanged, this
            [&]{ style()->polish(ui->myComboBox->lineEdit()); });