paky79
paky79

Reputation: 21

PyQt - trouble with reimplementing data method of QSqlTableModel

I'm a newbie with python and mainly with pyqt. The problem is simple: I have a QTableView and I want to "simply" change the color of some rows. Reading all around I found that the simplest solution should be to override the data method in the model in such a way:

class MyModel(QtSql.QSqlTableModel):

    def data(self,idx,role):
        testindex=self.index(idx.row(),idx.column(),idx.parent())
        if(role==QtCore.Qt.BackgroundRole):
            return QtGui.QColor(255,0,0)
        elif role == QtCore.Qt.DisplayRole:
            return QtSql.QSqlTableModel().data(testindex)

When I use this model reimplementation, the rows are changing color but the cell values disappear and the return statement QtSql.QSqlTableModel().data(testindex) is always None. I'm getting crazy to find out a solution. Could you help me?

Upvotes: 2

Views: 569

Answers (1)

ekhumoro
ekhumoro

Reputation: 120718

Your implementation is broken in a couple of ways: (1) it always returns None for any unspecified roles, (2) it creates a new instance of QSqlTableModel every time the display role is requested, instead of calling the base-class method.

The implementation should probably be something like this:

class MyModel(QtSql.QSqlTableModel):

    def data(self, index, role):
        if role == QtCore.Qt.BackgroundRole:
            return QtGui.QColor(255, 0, 0)
        return super(MyModel, self).data(index, role)

Upvotes: 2

Related Questions