通常您为此使用 QSortFilterProxyModel.filterAcceptsRow。
在我的应用程序中,我这样做:
class SortModel(QSortFilterProxyModel):
def __init__(self, parent=None):
super(SortModel, self).__init__(parent)
def filterAcceptsRow(self, source_row, source_parent):
# check if an item is currently accepted
accepted = super(SortModel, self).filterAcceptsRow(source_row, source_parent)
if accepted:
return True
# if it is not accepted may be item parent could be accepted
model = self.sourceModel()
# get item parent [In my app I use only two levels for items,
# so you need to make a function out of this to make it work for n levels ]
index = model.index(source_row, self.filterKeyColumn(), source_parent)
has_parent = model.itemFromIndex(index).parent()
# if there is a parent
if has_parent:
parent_index = self.mapFromSource(has_parent.index())
# check if parent is accepted
return super(SortModel, self).filterAcceptsRow(has_parent.row(), parent_index)
return accepted
如果您使用 Qt 5.10 禁用递归过滤或仅在需要时启用它:
def filterAcceptsRow(self, source_row, source_parent):
accepted = super(SortModel, self).filterAcceptsRow(source_row, source_parent)
if self.isRecursiveFilteringEnabled():
return accepted
else:
if accepted:
return True
...