我使用 PyQt 编写 QTableView 和 QAbstractItemModel 的自定义实现。我想创建一个按钮,通过调用重新实现的 rowRemoved 事件处理程序从 TableModel 中删除一行。由于某种原因,模型尝试为已删除的行创建行标题,这会导致崩溃。
以下是 removeRows
、headerData
和 rowCount
的实现。 self.alignment.sequences
是数据列表,每个 header 填充有 sequences.name
:
def removeRows(self, position, rows, parent=QModelIndex()):
print "removeRows called"
self.beginRemoveRows(parent, position, position + rows -1)
for i in range(int(rows)):
self.alignment.sequences.pop(position)
self.endRemoveRows()
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(str(col))
elif orientation == Qt.Vertical and role == Qt.DisplayRole:
try:
return self.alignment.sequences[col].name
except:
print "Exception: no header with index %s" % col
def rowCount(self, parent):
return len(self.alignment.sequences)
由于某种原因,我的应用程序崩溃了。其执行结果出现异常,并在 headerData
中捕获:
Exception: no header with index 16
GUI 为标题创建了空间,对应于已删除的行,但显然无法填充它。
你有什么想法吗,为什么 Qt 没有对行删除做出适当的 react ?谢谢。
最佳答案
乍一看,数据存储和 header 似乎来自同一个变量。因此,您可能已从删除行中删除了标题。如果您将它们保留为单独的变量,那么您的数据操作根本不会影响您的 header 。
另一件事是用通用异常来摆脱 Try except。这样您就可以看到您遇到的错误类型。
try:
return self.alignment.sequences[col].name
except (IndexError, AttributeError) as err:
print(err)
关于python - pyqt QTableView 删除行导致异常 : Qt attempts to create header for removed row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22039893/