Home > Mobile >  Customize ListItem contains colorful label, colorful label background not show?
Customize ListItem contains colorful label, colorful label background not show?

Time:05-18

I customize QListView and ListItem, the ListItem contain colorful label,but the colorful label not working?I can't find why the QLabel not show it's color.

Demo code

from qtpy.QtWidgets import *
from qtpy.QtCore import *
from qtpy.QtGui import *

class ListItem(QWidget):
    def __init__(self, color, info):
        super().__init__()
        lay = QHBoxLayout()
        self._colorLabel = QLabel()
        self._info = QLabel(info)

        lay.addWidget(self._colorLabel)
        lay.addWidget(self._info)
        self.setLayout(lay)

        self._colorLabel.setAutoFillBackground(True)
        self.setLabelColor(color)

    def setLabelColor(self, color):
        pal = self._colorLabel.palette()
        pal.setColor(QPalette.Window, color)
        self._colorLabel.setPalette(pal)

class ListWiget(QListWidget):
    def _addItem(self, item):
        tmpItem = QListWidgetItem()
        tmpItem.setSizeHint(item.sizeHint())
        self.addItem(tmpItem)
        self.setItemWidget(tmpItem, item)


app = QApplication([])

listW = ListWiget()
item = ListItem(Qt.red, "red")
item2 = ListItem(Qt.blue, "blue")
listW._addItem((item2))
listW._addItem(item)
listW.show()

app.exec()

The Picture
It always show white background?
enter image description here

CodePudding user response:

You have to use Base instead of Window:

def setLabelColor(self, color):
    pal = self._colorLabel.palette()
    pal.setColor(QPalette.Base, color)
    self._colorLabel.setPalette(pal)
  • Related