How to change (remove) selection/active color of QListWidget

倖福魔咒の 提交于 2019-12-06 07:16:40

I think you'd be better served using the style sheets to do this. Here's an example

QListWidget::item
{
    background: rgb(255,255,255); 
}
QListWidget::item:selected
{
    background: rgb(128,128,255);
}

::item indicates the individual items within the QListWidget, while :selected indicates the QListWidgetItems which are currently selected.

To then get the custom background on specific widgets, you could use custom style sheet properties. In your code, call something like this on the widget you want to apply a custom style on:

myList->setProperty( "Custom", "true" );

//  Updates the style.
style->unpolish( myList );
style->polish( myList );

Then in your style sheet, define the style for your custom property like so.

QListWidget::item[Custom="true"]
{
    background: rgb(128,255,128);
}

I found a suitable solution by using a delegate. So, there is no need to use QPalette; and for my problem the stylesheets will not work. This solution will also work when different rows (QListWidget or QTreeWidget) are needed to be colored in different colors, depending on some state.

The background color is set as described on the question:

item->setBackgroundColor(qcolor); // change color slot inside QListWidget class

In order to define rules how the widget is painted, I re-define the delegate:

class Delegate : public QStyledItemDelegate {};

Then I re-define Delegate's method paint(). There I define how to draw each row of my widget. More specifically, I only call custom drawing when the mouse hovering over an item, or that item is in selected state (those are the conditions when the row is selected by the light blue color which I want to avoid). The code looks like this:

void Delegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if((option.state & QStyle::State_Selected) || (option.state & QStyle::State_MouseOver))
    {
        // get the color to paint with
        QVariant var = index.model()->data(index, Qt::BackgroundRole);

        // draw the row and its content
        painter->fillRect(option.rect, var.value<QColor>());
        painter->drawText(option.rect, index.model()->data(index, Qt::DisplayRole).toString());
    }
    else
        QStyledItemDelegate::paint(painter, option, index);

    // ... 
}

Of course, do not forget to associate the QListWidget with Delegate:

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