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

vicrucann picture vicrucann · Mar 15, 2016 · Viewed 9.9k times · Source

In my QListWidget, there are some items that have non-default background color, I set them like so inside the custom QListWidget class:

item->setBackgroundColor(qcolor); // item is of type QListWidgetItem*

Those non-default colors that I set are distorted by the QListWidget's selection color. See an example:

enter image description here

Items three and four are supposed to be the same color, but they are not since the item four is selected, and thus the result color is a summation of original color and QListWidget's selection (active item?) color.

My question is how to edit or remove that selection color?

I tried inside my QListWidget (in special slot when I want to change the item's background color):

QPalette pal = this->palette();
pal.setColor(QPalette::Highlight, QColor(255,255,255,0));
this->setPalette(pal); // updated

But it did not produce any effect. what am I doing wrong? Is it a correct variable to set? Do I set it up inside QListWidget or inside its delegate?

Update: I tried using stylesheets as pointed by comment/answer, however, it will not be possible to use them for my application, because the items in my rows have 3 states (so I would need to use three colors). E.g., 3 states that correspond to three colors: pink for active, green for inactive and gray for the rest. When using stylesheets, I cannot set the custom property (let's say QListWidget::item[Inactive="true"]) to a single QListWidgetItem, but for the full QListWidget, and therefore it colors all the rows the same color.

Stylesheets were tried for similar problem here, and didn't work, therefore I make conclusion using stylesheets is not the way to go.

The background change method that I used originally works fine for my purpose, but I cannot figure out how to get rid of the default selection color (transparent light blue) which adds to the background color and produces the mixed color.

Answer

MildWolfie picture MildWolfie · Mar 15, 2016

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