如果展开,如何告诉 filterAcceptsRow 不要过滤 parent

how to tell filterAcceptsRow to not to filter parent if expanded

我有一个适用于所有根节点的可搜索树视图。但是,我不知道如何阻止它删除 parent 以在 children 中搜索。它仅在 parent 和 child 匹配搜索条件时有效。例如,如果我在示例中从图像中搜索“新鲜”,它将不会显示第三行,因为 parent 将被隐藏。

在 filterAcceptsRow 中,我只能访问代理模型,无法检查是否扩展了某些内容。至少我不知道该怎么做才能简单地忽略过滤器中的所有扩展项以允许在它们的 children.

中搜索

较新版本的 QT 内置了此功能 setRecursiveFilteringEnabled 但不幸的是,我有一段时间一直使用旧版本。


    def filterAcceptsRow(self, source_row, source_parent_index):

        model = self.sourceModel()
        source_index = model.index(source_row, 0, source_parent_index)

        # my naive attempt that only works for views that dynamically populate the children
        # that totally fails on statically popluated ones as it thinks that everythign is expanded
        # if model.hasChildren(source_index) and not model.canFetchMore(source_index):
        #     return True

        d = model.searchableData(source_index) #this simply returns a string that I can regex in the filter

        return self.isVisible(d) #some custom regex magic not important here

理想情况下,如果过滤器匹配 children(或 parent 本身)

中的任何内容,我希望保留 parent

如果 children 和 return 中的任何一个 True:[=13=,则需要递归调用过滤器函数 return True ]

def filterAcceptsRow(self, source_row, source_parent_index):
    model = self.sourceModel()
    source_index = model.index(source_row, 0, source_parent_index)
    for child_row in range(model.rowCount(source_index)):
        if self.filterAcceptsRow(child_row, source_index):
            return True
    d = model.searchableData(source_index)
    return self.isVisible(d)

显然,如果模型非常扩展,你应该考虑一些缓存,但你可能需要使用 QPersistentModelIndex 作为键,并覆盖你用来更新过滤器的任何函数(假设它们是以编程方式调用的,因为它们不是虚拟的并且为内部 Qt 实现(例如 QCompleter)覆盖它们将不起作用。