[PyQt] Custom delegates and alternating row colors on QTableView

Phil Thompson phil at riverbankcomputing.com
Sat Jun 5 14:56:40 BST 2010

On Tue, 1 Jun 2010 21:48:09 +0100, Ricardo Cruz <ricardommcruz at gmail.com>
> Hi there,
> I'm programming a small finance application and I use QTableViews
> intensively. It happens that for most of these tables I have special
> painting requirements and need a custom delegate. I am using
> QtyledItemDelegate as a base class. One of the things I would like the
> delegate to manage is the painting of alternate colors for each row.
> To achieve that, I used the option parameter of the paint method. This
> object is a QStyleOptionViewItem from which a QStyleOptionViewItemV2 can
> created and initiated. The features property of the
> would tell me if I am painting an alternate color or not provided the
> alternatingRowColors property of the QTableView is set to True. This way
> don't need to implement any alternate color mechanism in my code, I
> detect it and choose a color accordingly.
> The code would be something like;
>     def paint(self, painter, option, index):
>         style = QtGui.QStyleOptionViewItemV2(option)
>         self.initStyleOption(style, index)
>         painter.save()
>         if style.state & QtGui.QStyle.State_Selected:
>             painter.fillRect(option.rect,
> option.palette.highlight().color())
>             painter.setPen(option.palette.highlightedText().color())
>         elif style.features & QtGui.QStyleOptionViewItemV2.Alternate:
>             painter.fillRect(option.rect, QtGui.QColor(246,255,218))
>         else:
>             painter.fillRect(option.rect, QtGui.QColor(191,222,185))
>         QtGui.QStyledItemDelegate.paint(self, painter, option, index)
>         painter.restore()
> However at the moment and since I upgraded to PyQT 4.7.3,

>From what version? Is the version of Qt the same?

> the style.features
> property is not initiated properly and the code is always falling on the
> else statement, which means no alternate colors.
> So my question is if the above code should behave like I was expecting or
> not. It definitely worked before.
> But if not then what is the best way to implement this? Having a custom
> role
> that I can pass to the data method of the model to detect if I am
> an alternate row, or perhaps just use the index.row() to detect even and
> odd
> row numbers, or even use a Style?

Have you got a complete test case?


More information about the PyQt mailing list