[PyQt] Custom delegates and alternating row colors on QTableView

Ricardo Cruz ricardommcruz at gmail.com
Tue Jun 1 21:48:09 BST 2010


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 be
created and initiated. The features property of the QStyleOptionViewItemV2
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 I
don't need to implement any alternate color mechanism in my code, I merely
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, 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 painting
an alternate row, or perhaps just use the index.row() to detect even and odd
row numbers, or even use a Style?

Cheers,

--
Ricardo Cruz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20100601/de953a9f/attachment.html>


More information about the PyQt mailing list