使用QSortFilterProxyModel过滤QTreeView

时间:2015-04-10 13:25:58

标签: qt pyqt qt4 pyqt4 pyqt5

我有一棵这样的树:

标题1 header2 header3

节点1

- 节点2

---- node3 value1 value2

---- node4 value3 value4

等等...

我需要在同一行中过滤不同值的模型。 也就是说,如果value1与value2相同(相等),则跳过此行,否则 - 显示。

有一些示例代码:

class FindFilterProxyModel(QtCore.QSortFilterProxyModel):
def filterAcceptsRow(self, source_row, source_parent):
    if (self.filterAcceptsRowItself(source_row, source_parent)):
        return True

    if (self.hasAcceptedChildren(source_row, source_parent)):
        return True

    return False

def filterAcceptsRowItself(self, source_row, source_parent):
    return super(FindFilterProxyModel, self).\
    filterAcceptsRow(source_row, source_parent)

def hasAcceptedChildren(self, source_row, source_parent):
    model = self.sourceModel()
    sourceIndex = model.index(source_row, 0, source_parent)
    if not (sourceIndex.isValid()):
        return False

    childCount = model.rowCount(sourceIndex)
    if (childCount == 0):
        return False

    for i in range (childCount): 
        if (self.filterAcceptsRowItself(i, sourceIndex)):
            return True
        # recursive call -> NOTICE that this is depth-first searching,
        # you're probably better off with breadth first search...
        if (self.hasAcceptedChildren(i, sourceIndex)):
            return True

    return False

它递归地比较第一列中的值(将其用于搜索)。 我想将它与除第一列之外的所有列进行比较。

1 个答案:

答案 0 :(得分:0)

也许它会对某人有所帮助。此代码比较两列中的值。

class DiffFilterProxyModel(QtCore.QSortFilterProxyModel):
def filterAcceptsRow(self, source_row, source_parent):
    # Check if the model is valid
    model = self.sourceModel()
    if model is None:
        return False

    # get index for first column of the row
    src_index = model.index(source_row, 0, source_parent)

    # recursively compare the values in tree
    for i in range (model.rowCount(src_index)):
        child_index = src_index.child(i, 0)
        c1 = child_index.sibling(child_index.row(), 1).data()
        c2 = child_index.sibling(child_index.row(), 2).data()

        if (c1 != c2 or self.filterAcceptsRow(i, src_index)):
            return super(DiffFilterProxyModel, self).filterAcceptsRow(source_row, source_parent)                                                   

    c1 = src_index.sibling(src_index.row(), 1).data()
    c2 = src_index.sibling(src_index.row(), 2).data()

    return c1 != c2 and super(DiffFilterProxyModel, self).filterAcceptsRow(source_row, source_parent)

感谢grondek的帮助。