正确使用setBackground

dan*_*van 4 python pyqt pyside

希望对你来说很简单......

我一直在尝试设置QtListWidgetItem的背景颜色,但我没有太多运气 - 这可能是因为我没有正确使用QListWidgetItem ...在我的测试代码中我可以设置每三分之一的前景列表中的项目,但设置背景似乎没有任何效果.谁能发现我的愚蠢错误?

我在Qt 4.7上用PyQt4和PySide对它进行了测试

谢谢,丹

import sys
from PySide import QtCore, QtGui

class List(QtGui.QListWidget):
    def __init__(self):
        super(List, self).__init__()
        self.populate()

    def populate(self):
        for i in range(32):
            item = QtGui.QListWidgetItem(self)
            item.setText('%d'%i)

            if i % 3 == 0:
                brush = QtGui.QBrush()
                brush.setColor(QtGui.QColor('red'))
                item.setBackground(brush)

            if i % 3 == 1:
                brush = QtGui.QBrush()
                brush.setColor(QtGui.QColor('blue'))
                item.setForeground(brush)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    listw = List()
    listw.show()

    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

Ble*_*der 7

你真的不需要刷子.只需使用QColor:

item.setBackground(QtGui.QColor('red'))
Run Code Online (Sandbox Code Playgroud)