How do I Color a QTableView row in PyQt4

Mel melirizarry at gmail.com
Wed Feb 28 12:55:55 EST 2007


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 = QtSql.QSqlQueryModel.data(self, 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(QtCore.Qt.blue))
        return value

def initializeModel(model):
    model.setQuery("SELECT * FROM WaterOrder Where DateCanceled is
NULL AND ActDateTimeOff is NULL and ActDateTimeOn is NOT NULL")

offset = 0
views = []

def createView(title, model):
    global offset, views

    view = QtGui.QTableView()
    views.append(view)
    view.setModel(model)
    view.setWindowTitle(title)
    for i in range(model.columnCount()):
        view.resizeColumnToContents(i)
    view.setAlternatingRowColors(1)

    view.move(100 + offset, 100 + offset)
    offset += 20
    view.show()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    if not connection.createConnection():
        sys.exit(1)

    customModel = CustomSqlModel()
    initializeModel(customModel)
    createView(QtCore.QObject.tr(customModel, "Running Water"),
customModel)

    sys.exit(app.exec_())

*** End Code ***


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?

Thanks,
Mel




More information about the Python-list mailing list