QSqlQueryModel是一个很棒的数据库模型,但它是只读的.所以我重写了它的setData()和flags()方法.现在,我可以从QTableView编辑数据库表
但是当我发出dataChanged()时,QTableView不会刷新自身,当我在QTableView中编辑文本框并单击其他位置时,新值成功写入数据库,但是文本框的值恢复为旧值.我必须重新选择整个表,表现确实很差…
为什么?
class StudentsTableModel(QtSql.QSqlQueryModel):
def __init__(self):
QtSql.QSqlQueryModel.__init__(self)
self.LockedColumns = []
def flags(self, index):
flags = QtSql.QSqlQueryModel.flags(self, index)
if index.column() not in self.LockedColumns:
flags |= QtCore.Qt.ItemIsEditable
return flags
def setData(self, index, value, role):
primary_key_index = self.index(index.row(), 0)
name = self.data(primary_key_index)
field = self.record().fieldName(index.column())
self.update(name, field, value)
self.dataChanged.emit(self.index, self.index)
# Why DataView isn't refresh automatically when
# a dataChanged signal emited? Force re-select...
self.select(self.week)
return True
def update(self, name, field, value):
query = QtSql.QSqlQuery()
sql = ("UPDATE student_info SET '%s' = '%s' WHERE 学生姓名 = '%s'"
% (field, value, name))
query.exec(sql)
def select(self, week):
self.week = week
sql = ("SELECT 学生姓名,第%s周,小组 FROM student_info" % (week))
self.setQuery(sql)
解决方法:
查看此模型如何为您工作:
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
代替setQuery来设置表,我在主类中将具有以下内容:
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