如何在排序数据源后更新QAbstractTableModel和QTableView?

5 投票
1 回答
6159 浏览
提问于 2025-04-17 10:57

我有一个自定义的数据结构,想在一个PyQt应用程序中用QTableView来展示它。我使用了QAbstractTableModel的子类来和数据进行沟通。这个数据结构在一个单独的模块里,跟PyQt没有任何关系。

用QTableView来显示和编辑数据是可以的,但现在我想对数据进行排序,然后更新模型和视图。

我看了Qt的文档,了解了QAbstractTableModel和它的父类QAbstractItemModel,最开始我尝试了这个方法:

class MyModel(QtCore.QAbstractTableModel):
    __init__(self, data_structure):
        super().__init__()
        self.data_structure = data_structure

    # ...

    def sort_function(self):
        self.layoutAboutToBeChanged.emit()
        # custom_sort() is built into the data structure
        self.data_structure.custom_sort()
        self.layoutChanged.emit()

但是,这个方法没有更新视图。我还尝试在模型使用的所有数据上发出dataChanged信号,但这也没有更新视图。

我进一步研究了一下。如果我理解得没错,问题在于模型中的QPersistentModelIndexes没有得到更新,解决办法是要手动更新它们。

有没有更好的方法呢?如果没有,我该如何更新它们(最好是不用写一个新的排序函数来跟踪每个索引的变化)?

1 个回答

5

在custom_sort()这个函数里有个错误。修复了这个错误之后,我在这里描述的方法就可以正常工作了。

class MyModel(QtCore.QAbstractTableModel):
    __init__(self, data_structure):
        super().__init__()
        self.data_structure = data_structure

    # ...

    def sort_function(self):
        self.layoutAboutToBeChanged.emit()
        # custom_sort() is built into the data structure
        self.data_structure.custom_sort()
        self.layoutChanged.emit()

撰写回答