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

穿精又带淫゛_ 提交于 2019-12-30 09:56:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21440282/qt-how-to-change-the-highlight-color-of-a-specific-qcombobox-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!