排序数据源后如何更新QAbstractTableModel和QTableView? [英] How to update QAbstractTableModel and QTableView after sorting the data source?

查看:692
本文介绍了排序数据源后如何更新QAbstractTableModel和QTableView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义数据结构,我想使用QTableView在PyQt应用程序中显示它.我正在使用QAbstractTableModel的子类与数据进行通信.数据结构本身在一个单独的模块中,对PyQt一无所知.

I have a custom data structure that I want to display in a PyQt application using a QTableView. I'm using a subclass of QAbstractTableModel to communicate with the data. The data structure itself is in a separate module and knows nothing about PyQt.

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

Displaying and editing the data with the QTableView works, but now I'd like to sort the data and then update the model and view.

在阅读了QAbstractTableModel及其祖先QAbstractItemModel的Qt文档之后,我的第一种方法是尝试以下方法:

After reading the Qt documentation for QAbstractTableModel and its ancestor QAbstractItemModel, my first approach was to try this:

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信号,但这也无法更新视图.

However, this fails to update the view. I also tried emitting a dataChanged signal on all of the data being used by the model, but this failed to update the view as well.

我做了一些进一步的研究.如果我理解正确,那么问题在于模型中的QPersistentModelIndexes没有得到更新,解决方案是以某种方式手动更新它们.

I did some further research. If I understand correctly, the problem is that the QPersistentModelIndexes in the model are not getting updated, and the solution would be to manually update them somehow.

是否有更好的方法可以做到这一点?如果没有,我将如何更新它们(最好不必编写新的排序函数来跟踪每个索引更改)?

Is there a better way to do this? If not, how would I go about updating them (preferably without having to write a new sort function that tracks every index change)?

推荐答案

custom_sort()函数中存在错误.修复它之后,我在这里描述的方法行得通.

There was a bug in the custom_sort() function. After fixing it, the approach I described here works.

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()

这篇关于排序数据源后如何更新QAbstractTableModel和QTableView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆