2015-04-10 5 views
1

У меня есть дерево, как это:Фильтрация QTreeView с QSortFilterProxyModel

заголовка 1 header2 header3

node1

--node2

---- node3 значение1 значение2

- --- node4 value3 value4

И т.д. ...

Мне нужно отфильтровать модель для разных значений в той же строке. То есть, если значение1 является одинаковым (равным) со значением2, то пропустите эту строку, если нет - отобразите.

Существует некоторый пример кода:

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 

рекурсивно сравнивает значения в первом столбце (используется для поиска). И я хочу сравнить это со всеми столбцами, кроме первого.

+0

Вы сказали, что хотите, и предоставили некоторый код. Но каков ваш вопрос? Как я могу вам помочь? –

+0

Обратите внимание, что этот подход с фильтрацией родителей по свойствам их детей является хрупким, как только дети изменяются; из того, что я помню, filterAcceptsRow не будет вызываться для родителя снова, когда ребенок изменится, поэтому его состояние фильтра не будет обновлено. –

+0

@three_pineapples «Мне нужно отфильтровать модель для разных значений в той же строке. То есть, если значение1 одинаково (равно) со значением2, пропустите эту строку, если нет - отобразить». –

ответ

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 за его помощью.

Смежные вопросы