Akash Nil Akash Nil -3 years ago 219
Python Question

pyqt4: QListWidget: How to set different text and background colors to different items dynamically

I am new to PyQt. I want to design a list which will show different items with different background and text color. I am able to add items to my list but could not configure them to set different colors.

from PyQt4 import QtCore, QtGui

try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s

try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(786, 552)
self.mylist = QtGui.QListWidget(self.centralwidget)
self.mylist.setObjectName(_fromUtf8("mylist"))


self.mylist.addItem("item1")


self.mylist.addItem("item2")

if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())


My above code added to item named item1 and item2 in mylist. I want to set background color and text color to item1 blue and white ,and to item2 red and black. how could i do that??

Answer Source

The QListWidgetItem class has the setBackground():

QListWidgetItem.setBackground(your_color)

In your case:

self.mylist.item(0).setBackground(QtCore.Qt.blue)
# self.mylist.item(0).setBackground(QtGui.QColor("blue"))
# self.mylist.item(0).setBackground(QtGui.QColor(0, 0, 255))
self.mylist.item(1).setBackground(QtCore.Qt.white)
# self.mylist.item(1).setBackground(QtGui.QColor("white"))
# self.mylist.item(1).setBackground(QtGui.QColor(255, 255, 255))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download