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

编程入门 行业动态 更新时间:2024-10-16 21:32:41
本文介绍了排序数据源后如何更新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?

本文发布于:2023-07-09 21:26:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1088253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据源   QAbstractTableModel   QTableView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!