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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With