Nic*_*lle 4 python sorting pyqt qtableview qabstractitemmodel
我有一个自定义数据结构,我希望使用QTableView在PyQt应用程序中显示.我正在使用QAbstractTableModel的子类与数据进行通信.数据结构本身位于一个单独的模块中,对PyQt一无所知.
使用QTableView显示和编辑数据有效,但现在我想对数据进行排序,然后更新模型和视图.
在阅读QAbstractTableModel及其祖先QAbstractItemModel的Qt文档后,我的第一个方法是尝试这样做:
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()
Run Code Online (Sandbox Code Playgroud)
但是,这无法更新视图.我还尝试在模型使用的所有数据上发出dataChanged信号,但这也无法更新视图.
我做了一些进一步的研究.如果我理解正确,问题是模型中的QPersistentModelIndexes没有得到更新,解决方案是以某种方式手动更新它们.
有一个更好的方法吗?如果没有,我将如何更新它们(最好不必编写跟踪每个索引更改的新排序函数)?
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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5079 次 |
最近记录: |