How do I Color a QTableView row in PyQt4

David Boddie david at
Thu Mar 1 01:08:19 CET 2007

On Wednesday 28 February 2007 18:55, Mel wrote:

> I am currently porting an SQL centered Visual Basic application to run
> on Linux, Python, and Qt4.  Currently I am stumped on changing row
> colors in the QTableView widget.  My test code is based on code from
> the PyQt4  examples and looks like this:
> *** Start Code ***
> import sys
> from PyQt4 import QtCore, QtGui, QtSql
> import connection
> class CustomSqlModel(QtSql.QSqlQueryModel):
>     def data(self, index, role):
>         value =, index, role)
>         if value.isValid() and role == QtCore.Qt.DisplayRole:
>             if index.column() == 0:
>                 return QtCore.QVariant(value.toString().prepend("#"))
>             elif index.column() == 2:
>                 return QtCore.QVariant(value.toString().toUpper())
>         if role == QtCore.Qt.TextColorRole and index.column() == 1:
>             return QtCore.QVariant(QtGui.QColor(
>         return value

[Snipping the rest of the code to keep this post short.]

> Column 18 in the table shows a number from 1 to 3.  I would like to
> change the color of the row based on the value in column 18 but I have
> not been able to find any resources that show me how.  Can anyone lend
> a hand?

It's interesting to see that you subclassed QSqlQueryModel instead of
using a custom delegate to display the data. It's usually recommended
that you subclass QItemDelegate if you want to customize the way items
are represented, but you can also customize the model if you want.

What you can do is to check to see if the requested role is the
Qt.BackgroundRole and, if so, query the base class for the data in
column 18 in the same row. Then you can supply a different colour
(as a brush, actually) depending on the value you obtained.

        if role == QtCore.Qt.BackgroundRole:
            # Get the data from column 18.
            column18_data = index.sibling(index.row(), 18).data()
            # The data is stored in a QVariant, so we unpack it.
            integer_value = column18_data.toInt()[0] # just the value
            # Look up the associated color in a dictionary which you
            # have already defined, and return it.
            color = self.colors.get(integer_value, self.default_color)
            return QtCore.QVariant(QtGui.QBrush(color))

You might also find the following pages useful:

Good luck!


More information about the Python-list mailing list