Qt, how to change the highlight color of a specific QComboBox item

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

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 any color that the QComboBox is currently the highlight color will be when you select an item in the popup. I would like each QComboBox item to remain the same color. The images show the problem I am facing.

enter image description hereenter image description hereenter image description here

+4
source share
1 answer

If I understand the question correctly, you want to completely remove the selected color so that the element under the mouse cursor is highlighted only with a dotted border.

: , QItemDelegate ( QItemDelegate QComboBox). :

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);
     }
 };

, , QStyle::State_Selected, QItemDelegate::paint, drawBackground, , , .

comboBox->setItemDelegate (new SelectionKillerDelegate), QItemDelegate. .

, QStyle::State_HasFocus, , , - .

+4

Source: https://habr.com/ru/post/1524351/


All Articles