python - pyqt QTableView 删除行导致异常 : Qt attempts to create header for removed row

标签 python qt model-view-controller pyqt

我使用 PyQt 编写 QTableView 和 QAbstractItemModel 的自定义实现。我想创建一个按钮,通过调用重新实现的 rowRemoved 事件处理程序从 TableModel 中删除一行。由于某种原因,模型尝试为已删除的行创建行标题,这会导致崩溃。

以下是 removeRowsheaderDatarowCount 的实现。 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/

相关文章:

asp.net-mvc - ASP.NET MVC 的用户-组-权限用户界面设计

python - 用 Python 记录降雨量

python - Pysmell 使用 Textmate 安装错误?

python - 如何更新 matplotlib 中的绘图

excel - 在编写qt activex excel读/写代码时防止未安装excel时应用程序崩溃

macos - Qt 和 OpenGL OS X : GLSL shader version only 120 on Mountain Lion

ios - 如何让我的 TableView 选择打开我的模态视图?

python - Django channel 在 Windows 10 中安装失败

c++ - MeeGo 开发可行吗?

ios - UITableView 的实现,遵循 MVC 模式