[PyQt] Subclassing QSqlQueryModel, making one column checkable

Sibylle Koczian Sibylle.Koczian at t-online.de
Sun Aug 16 13:09:25 BST 2009


I want to do the following: get two normal columns and one boolean
expression computed by a subquery from my database table, put them into
a QSqlQueryModel and show one of the columns in a QListView. Works so far.

But I'd like to make this column checkable. At the start of the
application the state should depend on the value of my boolean
expression in another column. I get so far with the code shown below.

But then the user should be able to check and uncheck items in the view,
without changing either the text in the column or the value of the
boolean column of the model. I suppose I should overwrite setData, just
for the CheckStateRole, but how?

Or would it be better to use a QStandardItemModel, because
QStandardItems have all the methods I need?

Here is the code for the model:

class EigReiseModel(QtSql.QSqlQueryModel):

    def flags(self, index):
        flags = QtSql.QSqlQueryModel.flags(self, index)
        if index.column() == 1:
            flags |= QtCore.Qt.ItemIsUserCheckable
        return flags

    def data(self, index, role=QtCore.Qt.DisplayRole):
        zl = index.row()
        if index.column() == 1 and role == QtCore.Qt.CheckStateRole:
            idx2 = self.createIndex(zl, 2)
            if self.data(idx2).toBool():
                return QtCore.Qt.Checked
                return QtCore.Qt.Unchecked
            return QtSql.QSqlQueryModel.data(self, index, role)

##    def setData(self, index, value, role=QtCore.Qt.EditRole):
##        if index.column() == 1 and role == QtCore.Qt.CheckStateRole:
##            chk = value.toBool()
##            if chk:
##                ??? (check item, but how?)

Thank you for all hints,

Sibylle Koczian

More information about the PyQt mailing list