PySide6 QTableView按回车跳转单元格触发commitData警告问题
解决QTableView按回车跳转单元格时的"QAbstractItemView::commitData called with an editor that does not belong to this view"警告
问题原因
直接调用setCurrentIndex切换光标时,当前单元格的编辑器尚未完成数据提交就被强制切换,导致后续commitData信号触发时,编辑器已与视图脱离关联,从而抛出警告。
解决方案
先通过基类的keyPressEvent处理回车键的默认逻辑(完成数据提交、关闭编辑器),再执行光标跳转操作;若需要贴合电子表格操作习惯,跳转后可自动进入下一个单元格的编辑状态。
修改后的代码
class CustomTableView(QtWidgets.QTableView): def __init__(self): super().__init__() header = self.horizontalHeader() header.setStyleSheet("QHeaderView::section { background-color: lightgray; border: 1px solid black; }") row = self.verticalHeader() row.setStyleSheet("QHeaderView::section { background-color: lightgray; border: 1px solid black; }") row.setDefaultAlignment(Qt.AlignCenter) def keyPressEvent(self, event): if event.key() == Qt.Key_Return: # 处理回车键事件 # 先调用基类方法提交当前编辑数据并关闭编辑器 super().keyPressEvent(event) current_index = self.currentIndex() if current_index.isValid(): next_row = current_index.row() + 1 # 计算目标单元格索引 if next_row < self.model().rowCount(): next_index = self.model().index(next_row, current_index.column()) else: # 超出范围时回到当前列第一行 next_index = self.model().index(0, current_index.column()) self.setCurrentIndex(next_index) # 自动进入目标单元格编辑状态(可选,可根据需求删除该行) self.edit(next_index) event.accept() else: super().keyPressEvent(event) # 其他按键交由基类处理 class Main(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(WINTITLE) self.table = CustomTableView() df = pd.read_csv(CSVFILE, header=None, low_memory=False) self.model = TableModel(df) self.table.setModel(self.model) self.setCentralWidget(self.table)
补充说明
- 若不需要自动进入编辑状态,删除代码中的
self.edit(next_index)即可; - 该方案确保编辑器在光标切换前已完成数据提交并正常关闭,彻底避免了警告触发。
内容的提问来源于stack exchange,提问作者IT2138
相关产品推荐
相关产品推荐

