Qt World Summit: Submit your Presentation

Issues with subclassing a QSqlTableModel

  • Hello, I subclassed a QSqlTableModel (rowcount, columncount, data) but when I call the tableview.model().data(index.siblingAtColumn(0) an error occours (all the data are displayed correctly and the column 0 has never a NULL value, it contains an id)

    def data(self, index, role):
    if role == qtc.Qt.ForegroundRole:
    if index.column() == 3
    return qtg.QColor('red')
    return super().data(index, role)

    What am I doing wrong?

  • @cibas please provide a minimal and reproducible example

  • I wrote the example code above (sorry for the bad indentation).
    Meanwhile I discovered that when I try to access at "self.tableView.model().data(index)" this is the error:

    data() missing 1 required positional argument: 'role'

    This is not happening with the super class QSqlTableWidget (I never passed the role parameter)

    class TableMagModel(QSqlTableModel):
    def init(self):

    def data(self, index, role):
        if role == Qt.ForegroundRole:
            if index.column() == 3:
                return QColor('red')
        return QSqlTableModel.data(self, index, role)

  • @cibas
    I do not understand. You seem to quote an error message you receive, yet show code which does not cause the error to be raised?

    There is nothing wrong with self.tableView.model().data(index).

    However, you do not state whether you are using PyQt5, PyQt6, PySide2 or PySide6. Without that information it is not possible to give a definitive answer.

    On a separate note, in your subclass of QSqlTableModel where you define the __init__() method you would be better advised to define it with the extra optional parameters as per https://doc.qt.io/qtforpython-5/PySide2/QtSql/QSqlTableModel.html#PySide2.QtSql.PySide2.QtSql.QSqlTableModel.

  • @JonB sorry I'm using PyQt5

    The error message I get is raised by the line self.tableView.model().data(index)

    With the class QSqlTableModel this line works properly but though I subclassed it (I wrote the code) that line raise me an error

  • @cibas
    OK, got it! This is because in your subclass you have chosen to write:

    def data(self, index, role):

    Here you have made the role parameter compulsory, because you do not supply a default value, hence the error message. This is the same sort of issue as I mentioned with your __init__() definition. You should be more careful to look at the method(s) you are overriding and declare your overload signature to be exactly the same as the base method you are overriding. Thus here

    class TableMagModel(QSqlTableModel):
        def data(self, index, role=Qt.DisplayRole):

    which is how the base QSqlTableModel.data() is defined. Now the role parameter from the caller is optional, and will default to Qt.DisplayRole if not supplied.

  • @JonB Thank You!!!
    I will listen you advices

Log in to reply