动态填充数据时如何限制PyQt表格行数且不追加空白行
问题根源
你当前的实现存在两个核心问题导致出现空白行:
- 删行操作未通知视图:直接修改内部
_data数组删除首行,但没有发送Qt模型对应的行删除信号,QTableView不知道数据行数已经减少,会按照插入后的行数渲染,超出实际数据的部分就显示为空白行。 - 长度判断逻辑错误:你使用
append之前的数组长度和最大行数对比,且判断阈值错误,导致长度达到上限后实际没有触发删行逻辑。
修复方案
调整appendData的执行逻辑,删行时主动通知视图,修正长度判断规则:
def appendData(self, oneRecord): # 达到行数上限时先删除最早的首行 if len(self._data) >= TABLE_MAX_LINE: self.rowsAboutToBeRemoved.emit(QModelIndex(), 0, 0) del self._data[0] self.rowsRemoved.emit(QModelIndex(), 0, 0) # 再插入新数据 insert_pos = len(self._data) self.rowsAboutToBeInserted.emit(QModelIndex(), insert_pos, insert_pos) self._data.append(oneRecord) self.rowsInserted.emit(QModelIndex(), insert_pos, insert_pos)
完整可运行代码
from PyQt5.QtCore import * from PyQt5.QtWidgets import * TABLE_MAX_LINE = 10 class Model(QAbstractTableModel): def __init__(self) -> None: super().__init__() self._data = [] self._columns = list("ABCD") def appendData(self, oneRecord): # 达到行数上限时先删除最早的首行 if len(self._data) >= TABLE_MAX_LINE: self.rowsAboutToBeRemoved.emit(QModelIndex(), 0, 0) del self._data[0] self.rowsRemoved.emit(QModelIndex(), 0, 0) # 再插入新数据 insert_pos = len(self._data) self.rowsAboutToBeInserted.emit(QModelIndex(), insert_pos, insert_pos) self._data.append(oneRecord) self.rowsInserted.emit(QModelIndex(), insert_pos, insert_pos) def headerData(self, section: int, orientation: Qt.Orientation, role: int): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return self._columns[section] elif orientation == Qt.Vertical and role == Qt.DisplayRole: return f"{section}" def rowCount(self, parent) -> int: return len(self._data) def columnCount(self, parent) -> int: return len(self._columns) def data(self, index, role: int): if index.isValid() and role == Qt.DisplayRole: return self._data[index.row()][index.column()] app = QApplication([]) v = QTableView() v.show() model = Model() v.setModel(model) def appendData(): import random r = lambda: random.randint(1, 10000) model.appendData([r(), r(), r(), r()]) timer = QTimer() timer.setInterval(1000) timer.timeout.connect(appendData) timer.start() app.exec()
修改后表格会始终保持最多10行有效数据,不会出现空白行,新增数据时最早的第一条数据自动移除,新数据追加在表格末尾。
内容的提问来源于stack exchange,提问作者jett chen
相关产品推荐
相关产品推荐

