qtselectionhighlightqcomboboxselectedtext

Is it possible to highlight only the text of the current QComboBox Selection?


I want only text of the current QComboBox Selection to be highlighted instead of the whole area

until the down arrow. to illustrate better I want something like this: enter image description here

instead of this: enter image description here

Is this possible? If yes how? I searched online, tried a couple of things but cannot make it work. Any ideas or suggestions? Thanks in advance.


Solution

  • What you are describing is the default behavior for an editable combo box. In that case, simply set

    QComboBox* box = new QComboBox();
    box->setEditable(true);
    

    If you don't want your QComboBox to be editable, then it's unintuitive, but what you want to do can still be accomplished.

    If you set the QComboBox to be editable, while setting the underlying line edit to be read only, then the highlighting will look like in your picture, but there won't be any cursor and the user won't be able to edit the combo box items. Here's an example:

    QComboBox* box = new QComboBox();
    box->addItems(QStringList() << "None (Min Profit)" << "All (Max Profit)");
    box->setEditable(true);
    box->lineEdit()->setReadOnly(true);
    
    // c++11 style, but this can also be done using SIGNAL(...) and SLOT(...)
    connect(box, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), [box]
    {
        box->lineEdit()->selectAll();
    });
    

    And here's an image of the result (I'm on Windows 10 so the styling is a bit funny)

    Working combobox

    My 2 cents: While it can be done, the default Qt highlighting scheme may be more intuitive to your users for non-editable items.