QSqlQueryModel
is a great database model, but it is read only. So I rewrite its setData()
and flags()
method. Now, I can edit my database
See how if this model works for you:
class sqlTableModel(QSqlTableModel):
def __init__(self, parent=None):
super(sqlTableModel, self).__init__(parent)
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.EditRole:
value = value.strip() if type(value) == str else value
return super(sqlTableModel, self).setData(index, value, role)
def flags(self, index):
itemFlags = super(sqlTableModel, self).flags(index)
if index.column() != 0:
return itemFlags | Qt.ItemIsEditable
return itemFlags ^ Qt.ItemIsEditable # First column not editable
Instead of setQuery
, to set the table I would have something like this in the main class:
def setDatabase(self, nameDatabase):
self.database = QSqlDatabase.addDatabase("QSQLITE")
self.database.setDatabaseName(nameDatabase)
return self.database.open()
def setTable(self, nameTable):
self.model = sqlTableModel(self)
self.model.setEditStrategy(QSqlTableModel.OnManualSubmit)
self.model.setTable(nameTable)
self.model.select()
self.view.setModel(self.model)
def saveTable(self):
if self.model.submitAll():
return True
self.model.database().rollback()
return False