PyQt表格单元格动态自动补全实现咨询(支持自定义补全列表)
实现PyQt表格单元格独立动态补全的方案
我刚好做过类似的功能,给你一个完美适配需求的实现方案,既能让每个单元格拥有独立的补全列表,还能像你期望的那样用类似setItem的方式给指定单元格设置补全内容。
核心思路
- 给
QTableWidget扩展一个自定义方法,专门用来存储每个单元格的补全列表 - 让自定义的
ItemDelegate在创建编辑器时,根据当前单元格的位置去获取对应的补全列表 - 支持动态修改单元格的补全列表,切换单元格时自动加载对应列表
完整实现代码
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class CustomTableWidget(QTableWidget): def __init__(self, parent=None): super().__init__(parent) # 用字典存储每个单元格的补全列表,键是(row, column)元组 self.cell_completer_lists = {} def setCellCompleterList(self, row, column, completer_list): """给指定单元格设置补全列表""" self.cell_completer_lists[(row, column)] = completer_list def getCellCompleterList(self, row, column): """获取指定单元格的补全列表,没有则返回默认空列表""" return self.cell_completer_lists.get((row, column), []) class TableItemCompleter(QStyledItemDelegate): def __init__(self, parent=None): super().__init__(parent) def createEditor(self, parent, styleOption, index): editor = QLineEdit(parent) # 获取当前单元格对应的补全列表 table_widget = index.model().parent() completer_list = table_widget.getCellCompleterList(index.row(), index.column()) # 如果有补全列表就设置,没有则不启用补全(也可以设默认列表) if completer_list: autoComplete = QCompleter(completer_list) editor.setCompleter(autoComplete) return editor class mainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.initUI() def initUI(self): self.center_window = centerWindow(parent=self) self.setCentralWidget(self.center_window) class centerWindow(QWidget): def __init__(self, parent=None): super().__init__(parent) # 使用我们自定义的TableWidget table = CustomTableWidget() table.setItemDelegate(TableItemCompleter()) table.setRowCount(5) table.setColumnCount(2) # 给不同单元格设置独立的补全列表 table.setCellCompleterList(0, 0, ['苹果', '香蕉', '橘子']) table.setCellCompleterList(0, 1, ['红色', '黄色', '绿色']) table.setCellCompleterList(1, 0, ['牛肉', '猪肉', '鸡肉']) table.setCellCompleterList(2, 1, ['北京', '上海', '广州']) vbox = QVBoxLayout(self) vbox.addWidget(table) self.setLayout(vbox) if __name__ == '__main__': app = QApplication.instance() or QApplication(sys.argv) ex = mainWindow() ex.show() sys.exit(app.exec_())
关键部分解释
CustomTableWidget类:
- 新增了
cell_completer_lists字典,用来存储每个单元格的补全列表,键是(row, column)的元组,确保每个单元格唯一对应 setCellCompleterList方法就是你想要的类似setItem的操作,传入行、列和补全列表即可getCellCompleterList方法负责读取对应单元格的补全列表,没有的话返回空列表
- 新增了
TableItemCompleter类:
- 在
createEditor方法里,通过index.model().parent()获取到表格实例 - 然后调用表格的
getCellCompleterList方法拿到当前单元格的补全列表,再设置给编辑器的QCompleter
- 在
动态更新支持:
- 如果你需要在程序运行中动态修改某个单元格的补全列表,直接再次调用
setCellCompleterList即可,下次编辑该单元格时会自动加载新的列表
- 如果你需要在程序运行中动态修改某个单元格的补全列表,直接再次调用
这样实现后,每个单元格的补全列表完全独立,切换单元格时编辑器会自动加载对应的补全内容,完全满足你的需求。
内容的提问来源于stack exchange,提问作者Stephan
相关产品推荐
相关产品推荐

