QTableView修改单元格内容后格式丢失,如何修改代码保留格式?
QTableView修改单元格后保留格式的解决方法
修改QTableView的一个或多个单元格内容后,每个被修改的单元格都会丢失其原有格式。
原代码:
... class TableModel(QtCore.QAbstractTableModel): def __init__(self, data): super(TableModel, self).__init__() self._data = data def data(self, index, role): if index.isValid(): if role == Qt.DisplayRole or role == Qt.EditRole: value = self._data[index.row()][index.column()] return str(value) if role == Qt.TextAlignmentRole: value = self._data[index.row()][index.column()] if isinstance(value, int): return Qt.AlignVCenter + Qt.AlignRight if role == Qt.ForegroundRole: value = self._data[index.row()][index.column()] if (isinstance(value, int) and value < 0): return QtGui.QColor('red') def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole: self._data[index.row()][index.column()] = value self.dataChanged.emit(index, index, (Qt.DisplayRole, Qt.TextAlignmentRole, Qt.ForegroundRole,)) return True return False def rowCount(self, index): return len(self._data) def columnCount(self, index): return len(self._data[0]) def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
问题原因
问题出在setData方法中:用户编辑单元格输入的内容是字符串类型,直接存入_data后,后续data方法里判断isinstance(value, int)的条件不再成立,导致对齐方式、文字颜色这些格式规则无法触发。
修改方案
修改setData方法,将用户输入的内容尝试转换为整数,保持数据类型与原有数据一致;同时处理转换失败的情况,避免程序报错。
修改后的代码:
... class TableModel(QtCore.QAbstractTableModel): def __init__(self, data): super(TableModel, self).__init__() self._data = data def data(self, index, role): if index.isValid(): if role == Qt.DisplayRole or role == Qt.EditRole: value = self._data[index.row()][index.column()] return str(value) if role == Qt.TextAlignmentRole: value = self._data[index.row()][index.column()] if isinstance(value, int): return Qt.AlignVCenter + Qt.AlignRight if role == Qt.ForegroundRole: value = self._data[index.row()][index.column()] if (isinstance(value, int) and value < 0): return QtGui.QColor('red') def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole: # 尝试将输入转换为整数,保持数据类型一致 try: converted_value = int(value) self._data[index.row()][index.column()] = converted_value except ValueError: # 转换失败则保留字符串类型 self._data[index.row()][index.column()] = value # 通知视图数据已变更,触发格式刷新 self.dataChanged.emit(index, index, (Qt.DisplayRole, Qt.TextAlignmentRole, Qt.ForegroundRole,)) return True return False def rowCount(self, index): return len(self._data) def columnCount(self, index): return len(self._data[0]) def flags(self, index): return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
说明
- 当用户输入数字时,转换为整数存入,
data方法里的格式判断逻辑依然生效,对齐方式和文字颜色会保留 - 如果输入非数字内容,转换失败则存入字符串,此时不会触发整数对应的格式规则,按默认方式显示
内容的提问来源于stack exchange,提问作者Th.Fr.
相关产品推荐
相关产品推荐

