Customizing List View Items
Challenge: Fill in the gaps in the code.
Subclassing QListViewItem
To draw custom list view items, we need to subclass QListViewItem:
from qt import QBrush, QFont, QFontMetrics, QListViewItem, QPen, Qt
class ListViewItem(QListViewItem):
normal_brush = QBrush(Qt.white)
highlighted_brush = QBrush(Qt.white)
normal_pen = QPen(Qt.black)
highlighted_pen = QPen(Qt.red)
def __init__(self, key, *args):
QListViewItem.__init__(self, *args)
self.pen = self.normal_pen
self.brush = self.normal_brush
Painting
The paintCell method allow us to draw the list view items in our preferred style. We can always use the QListViewItem base class to draw anything we are unsure about:
def paintCell(self, painter, colour_group, column, width, alignment):
if self.isSelected():
QListViewItem.paintCell(self, painter, colour_group, column, width, alignment)
else:
painter.save()
painter.fillRect(0, 0, width, self.height(), self.brush)
painter.setFont(self.fonts[column])
painter.setPen(self.pen)
painter.drawText(0, QFontMetrics(self.fonts[column]).ascent(), self.text(column))
painter.restore()
Highlighting items
We can highlight the text in a particular column by calling a custom method. This just changes the pen and brush colours for the text in that column:
def setHighlighted(self, column, enable):
if enable:
self.pen = self.highlighted_pen
self.brush = self.highlighted_brush
else:
self.pen = self.normal_pen
self.brush = self.normal_brush
self.listView().triggerUpdate()
Other issues
The font needs to be set for the text in any new columns that are created:
def setText(self, column, text):
while column >= len(self.fonts):
font = QFont()
self.fonts.append(font)
QListViewItem.setText(self, column, text)
PyQt Wiki