【问题标题】:Filter QTreeView to return nodes when matching with root OR child node与根或子节点匹配时过滤 QTreeView 以返回节点
【发布时间】:2017-05-11 19:59:15
【问题描述】:

我有一个 QTreeVIew,通过 QAbstractItemModel 填充了数据,我可以使用 QSortFilterProxyModel.setFilterRegExp 过滤视图,但如果我的过滤字符串与根节点不匹配,则不返回子节点之间的匹配项。换句话说,我用来在节点之间查找匹配的字符串必须匹配根节点才能返回任何内容。

我想做的是让所有节点及其各自的父节点和子节点在匹配时返回到 QTreeView。下面的树显示了我在搜索 cat 时希望返回到 QTreeView 的结果

Animals
   cats
Cats
   kittens
   cat
       cats
       mice
       lice
Cars
   fantasy cars
       Catmobile

当我现在搜索 cat 时,返回的只是

Cats
   cats
       cats

【问题讨论】:

    标签: python-3.x filtering pyqt5 qtreeview


    【解决方案1】:

    通常您为此使用 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
        ...
    

    【讨论】:

      猜你喜欢
      • 2013-03-27
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多