Question

I'm trying to make the highlight transparent for a QComboBox. The color of this QComboBox also changes based on the selected index. Here is my best solution so far:

switch(comboBox->currentIndex())
{
case 0:
    comboBox->setStyleSheet("QWidget {color:black}");
    break;

case 1:
    comboBox->setStyleSheet("QWidget {background-color:red; color:white;}");
    break;

case 2:
    comboBox->setStyleSheet("QWidget {background-color:green; color:white;}");
    break;
}


comboBox->setItemData(0, QColor(Qt::white), Qt::BackgroundRole);
comboBox->setItemData(0, QColor(Qt::black), Qt::ForegroundRole);
comboBox->setItemData(1, QColor(Qt::red), Qt::BackgroundRole);
comboBox->setItemData(1, QColor(Qt::white), Qt::ForegroundRole);
comboBox->setItemData(2, QColor(Qt::darkGreen), Qt::BackgroundRole);
comboBox->setItemData(2, QColor(Qt::white), Qt::ForegroundRole);

QPalette p = comboBox->palette();
p.setColor(QPalette::Highlight, Qt::transparent);
comboBox->setPalette(p);

p = comboBox->view()->palette();
p.setColor(QPalette::Highlight, Qt::transparent);

comboBox->view()->setPalette(p);

The problem is that whatever color the QComboBox currently is is what the highlight color will be when selecting an item in the popup. I would like each QComboBox item to stay the same color. The images show the problem I'm having.

enter image description here enter image description here enter image description here

Was it helpful?

Solution

If I understand the question correctly you want to completely remove highlighted color so the item under mouse cursor would only be distinguished by the dotted frame.

The one way to do this goes as follows: we create class inherited from QItemDelegate (Normally simple QItemDelegate is responsible for drawing QComboBox items). We override paint function like this:

class SelectionKillerDelegate : public QItemDelegate
{
    virtual void paint(QPainter *painter,
        const QStyleOptionViewItem &option,
        const QModelIndex &index) const override
     {
         QStyleOptionViewItem myOption = option;
         myOption.state &= (~QStyle::State_Selected);
         QItemDelegate::paint (painter, myOption, index);
     }
 };

Basically we're just using normal paint function function but pretend that all the items don't have QStyle::State_Selected which is being checked in several functions inside QItemDelegate::paint, most importantly in drawBackground which is sadly not virtual.

When we're just using comboBox->setItemDelegate (new SelectionKillerDelegate) to make our delegate be used instead of simple QItemDelegate. That's all.

The good thing is that focused item is determined using QStyle::State_HasFocus so dotted frame for item pointed by mouse cursor will still be visible even with this delegate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top