Custom QStyledItemDelegate: Add Bold Elements

So here is the story:

I have a QListview that uses QSqlQueryModel to populate it. Since some elements must be displayed in bold depending on the value of the hidden model column, I decided to create my own custom delegate. I am using PyQT 4.5.4, and thus inheriting from QStyledItemDelegate is a way of navigating according to the docs. I got his job, but there are some problems with him.

Here is my solution:

class TypeSoortDelegate(QStyledItemDelegate): def paint(self, painter, option, index): model = index.model() record = model.record(index.row()) value= record.value(2).toPyObject() if value: painter.save() # change the back- and foreground colors # if the item is selected if option.state & QStyle.State_Selected: painter.setPen(QPen(Qt.NoPen)) painter.setBrush(QApplication.palette().highlight()) painter.drawRect(option.rect) painter.restore() painter.save() font = painter.font pen = painter.pen() pen.setColor(QApplication.palette().color(QPalette.HighlightedText)) painter.setPen(pen) else: painter.setPen(QPen(Qt.black)) # set text bold font = painter.font() font.setWeight(QFont.Bold) painter.setFont(font) text = record.value(1).toPyObject() painter.drawText(option.rect, Qt.AlignLeft, text) painter.restore() else: QStyledItemDelegate.paint(self, painter, option, index) 

The problems I'm currently facing are:

  • ordinary (not bold) elements are slightly indented (a few pixels). This is probably the default behavior. I could insert my element in bold, but what happens then under a different platform?
  • Usually, when I select items, there is a small border with a dashed line around it (is Windows by default?). Here I could also draw it, but I want to stay as dear as possible.

Now the question is:

Is there another way to create a custom delegate that only changes the font weight when a condition is met and leaves everything else untouched?

I also tried:

 if value: font = painter.font() font.setWeight(QFont.Bold) painter.setFont(font) QStyledItemDelegate.paint(self, painter, option, index) 

But this does not seem to affect the appearance. No errors, just default behavior and are not in bold.

All suggestions are welcome!

+4
source share
1 answer

I have not tested this, but I think you can do:

 class TypeSoortDelegate(QStyledItemDelegate): def paint(self, painter, option, index): get value... if value: option.font.setWeight(QFont.Bold) QStyledItemDelegate.paint(self, painter, option, index) 
+3
source

All Articles