PyQt - QTableView doesn't respond dataChanged signal?

后端 未结 1 1308
别跟我提以往
别跟我提以往 2021-01-24 01:44

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

相关标签:
1条回答
  • 2021-01-24 02:15

    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
    
    0 讨论(0)
提交回复
热议问题