为QListWidg中的指定项设置不同的颜色

2024-04-29 21:50:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个QListWidget,我想在列表的每一项中添加边框底部,并为项设置背景色,我想为特定项设置不同的背景色。 所以我使用my_list.setStyleSheet("QListWidget::item { border-bottom: 1px solid red; background-color: blue;}")并将背景色设置为我使用的特定项item.setBackground(QtGui.QColor("#E3E3E3"))

问题是我设置了不同颜色的指定项没有得到该颜色。


Tags: 列表颜色myreditemlistcolor边框
1条回答
网友
1楼 · 发布于 2024-04-29 21:50:45

不能在小部件上使用样式表和样式设置的组合-样式表将覆盖单个项上的任何设置。例如,下面的代码对每个项使用setBackground来更改背景色。

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

colors = [ '#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666']

class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        w = QListWidget()
        for n in range(8):
            i = QListWidgetItem('%s' % n)
            i.setBackground( QColor(colors[n]) )
            w.addItem(i)

        self.setCentralWidget(w)

        self.show()


app = QApplication([])
w = MainWindow()
app.exec_()

结果输出:

enter image description here

但是,如果在结果中添加样式表行,则为(第二行只有下边框):

enter image description hereenter image description here

不幸的是,没有办法设置物品的边框和颜色。但是,可以做的是插入一个自定义小部件作为列表项,或者use an item delegate来绘制该项。这使您可以完全控制外观,但您必须自己处理绘图。下面是使用自定义委托执行此操作的示例:

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

colors = [ '#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666']


class MyDelegate(QItemDelegate):
    def __init__(self, parent=None, *args):
        QItemDelegate.__init__(self, parent, *args)

    def paint(self, painter, option, index):
        painter.save()

        # set background color
        painter.setPen(QPen(Qt.NoPen))
        if option.state & QStyle.State_Selected:
            # If the item is selected, always draw background red
            painter.setBrush(QBrush(Qt.red))
        else:
            c = index.data(Qt.DisplayRole+1) # Get the color
            painter.setBrush(QBrush(QColor(c)))

        # Draw the background rectangle            
        painter.drawRect(option.rect)

        # Draw the bottom border
        # option.rect is the shape of the item; top left bottom right
        # e.g. 0, 0, 256, 16 in the parent listwidget
        painter.setPen(QPen(Qt.red))        
        painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())

        # Draw the text
        painter.setPen(QPen(Qt.black))
        text = index.data(Qt.DisplayRole)
        # Adjust the rect (to pad)
        option.rect.setLeft(5)
        option.rect.setRight(option.rect.right()-5)
        painter.drawText(option.rect, Qt.AlignLeft, text)

        painter.restore()


class MainWindow(QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        de = MyDelegate(self)
        w = QListWidget()
        w.setItemDelegate(de)
        for n in range(8):
            s = '%s' % n
            i = QListWidgetItem()
            i.setData(Qt.DisplayRole, s) # The label
            i.setData(Qt.DisplayRole+1, colors[n]) # The color
            w.addItem(i)

        self.setCentralWidget(w)

        self.show()


app = QApplication([])
w = MainWindow()
app.exec_()

输出如下:

enter image description here

使用委托的方法是定义一个paint方法,该方法接受一个QPainter对象(使用该对象进行实际绘制)、一个option参数(包含项的矩形(相对于父小部件)和一个index,通过该参数可以检索项数据。然后使用QPainter上的方法绘制项目。

在上面的例子中,我们使用它传递项标签(在位置Qt.DisplayRole)和十六进制颜色(在位置Qt.DisplayRole+1)。ItemDisplayRole的名称文档列出了其他定义的数据“角色”,但在大多数情况下,您可以忽略这些角色。

相关问题 更多 >