Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetBackGround on a QListWidgetItem does not work anymore after setting a stylesheet to QListWidgetItem

Tags:

qt

I am trying to make a QListWidget with QListWidgetItems. I want the QListWidgetItems to have a border and a background e.g. Green. The selected item should have another background e.g. Red. I tried to create the border with a stylesheet. This works fine. But I an not able to set the individual background color of the items anymore.

Below piece of code I am using

QListWidget *listWidget = new QListWidget();
QListWidgetItem *wi = new QListWidgetItem;
wi->setText("greenbg");
wi->setBackgroundColor(Qt::green);
listWidget->addItem(wi);

listWidget->setStyleSheet( "QListWidget::item {border-style: solid; border-width:1px; border-color:black;}");

QListWidgetItem *wi2 = new QListWidgetItem;
wi2->setText("redbg");
wi2->setBackgroundColor(Qt::red);
listWidget->addItem(wi2);
listWidget->show;

This shows the list transparent. When the setStyleSheet line is removed the items are green and red. What am I doing wrong or is it not possible and should I use a custom Widget?

like image 854
Marco de Bakker Avatar asked Feb 16 '23 05:02

Marco de Bakker


1 Answers

CSS is overriding the values you set there. Try to set the background color also in CSS:

listWidget->setStyleSheet( 
  "QListWidget::item {"
     "border-style: solid;" 
     "border-width:1px;" 
     "border-color:black;" 
     "background-color: green;"
  "}"
  "QListWidget::item:selected {"
     "background-color: red;"
  "}");

Notice that you can specify different style for different states (ie. that item is selected).

Example and other information here.

like image 127
Johny Avatar answered May 22 '23 00:05

Johny