Skip to main content
 首页 » 编程设计

python之编辑 QTableView 单元格值

2025年05月04日17findumars

如何让 QTableView 单元格在编辑时保持其原始值?当我开始编辑单元格时,它会自动清除。我到处搜索,找不到任何指向某处的指针。我的模型 View 实现:

class BlockViewModel(QAbstractTableModel): 
 
    def __init__(self, structure, data): 
        QAbstractTableModel.__init__(self) 
        self._data = data 
        self._struct = structure 
 
        for i, s in enumerate(structure): 
            cmnt = s['comment'] 
            name = cmnt if cmnt else s['name'] 
            self.setHeaderData(i, Qt.Horizontal, name) 
 
    def rowCount(self, parent=QModelIndex()): 
        return len(self._data) 
 
    def columnCount(self, parent = QModelIndex()): 
        return len(self._struct) 
 
    def data(self, index, role): 
        if role == Qt.DisplayRole: 
            try: 
                row = index.row() 
                col = index.column() 
                name = self._struct[col]['name'] 
                return self._data[row][name] 
            except: 
                pass 
        elif role == Qt.CheckStateRole: 
            return None 
 
        return None 
 
    def flags(self, index): 
        flags = super(self.__class__,self).flags(index) 
 
        flags |= Qt.ItemIsEditable 
        flags |= Qt.ItemIsSelectable 
        flags |= Qt.ItemIsEnabled 
        flags |= Qt.ItemIsDragEnabled 
        flags |= Qt.ItemIsDropEnabled 
 
        return flags 
 
    def headerData(self, section, orientation, role = Qt.DisplayRole): 
        if role != Qt.DisplayRole: 
            return None 
 
        if orientation == Qt.Horizontal: 
            cmnt = self._struct[section]['comment'] 
            return cmnt if cmnt else self._struct[section]['name'] 
        else: 
            return str(section) 
 
    def setData(self, index, value, role=Qt.EditRole): 
        row = index.row() 
        col = index.column() 
        name = self._struct[col]['name'] 
        self._data[row][name] = value 
        self.emit(SIGNAL('dataChanged()')) 
        return True 

请您参考如下方法:

data 方法负责始终显示您的数据。在编辑时,它使用 EditRole。因此,修改您的 data 方法以在 EditRole 中显示与 DisplayRole 相同的值,如下所示:

def data(self, index, role): 
    if role == Qt.DisplayRole or role == Qt.EditRole: 
        try: 
            row = index.row() 
            col = index.column() 
            name = self._struct[col]['name'] 
            return self._data[row][name] 
        except: 
            pass 
    elif role == Qt.CheckStateRole: 
        return None 
 
    return None