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')
else:
return super().data(index, role)What am I doing wrong?
-
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):
super().init()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. -
-
@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 hereclass TableMagModel(QSqlTableModel): def data(self, index, role=Qt.DisplayRole):
which is how the base
QSqlTableModel.data()
is defined. Now therole
parameter from the caller is optional, and will default toQt.DisplayRole
if not supplied.