PyQt - QTableView不响应dataChanged信号?

时间:2012-12-22 09:16:03

标签: python qt user-interface qt4 pyqt

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)

1 个答案:

答案 0 :(得分:0)

了解此模型是否适合您:

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