Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use QSortFilterProxyModel to filter a tree model that only display children nodes with their parents?

I have a working tree model derived from QAbstractItemModel and I wish to filter it using a QSortFilterProxyModel subclass to display only children nodes of certain criteria. For example I have the following tree:

A
- B
-- C1
-- C1
-- C1
--- C2
- D
- E

I want to filter this tree with the condition that the node has name == C1 and display only the nodes with C1 and their children like this:

C1
C1
C1
- C2

I already have a subclass with filterAcceptsRow() re-implemented that can partially do what I want but it will still show the parent and grandparent of C1 nodes:

A
- B
-- C1
-- C1
-- C1
--- C2

I think this is because for children nodes to even be considered, their parent has to pass the filterAcceptsRow() test, am I right? How can I implement filterAcceptRows() or other methods such that it can do what I have described?

I have asked this question sometime back in qtcentre and qtforum but did not get any useful reply. I tried to move the indices of the QSortFilterProxyModel subclass directly using beginMoveRows and endMoveRows inside filterAcceptsRow() but that just crashes the test application due to dangerous const_cast.

like image 626
ksming Avatar asked Sep 27 '11 02:09

ksming


2 Answers

Okay, I've found a solution to my problem. Just use QTreeView::setRootIndex() with index B as the input argument. Index B becomes the root index of the QTreeView, which is hidden and only its children are shown in full.

I felt really dumb after finding this solution. Guess I was too focused on using the proxy model to modify how the data is presented, I had totally forgotten about QTreeView.

like image 63
ksming Avatar answered Oct 16 '22 18:10

ksming


I dont think this is possible to achive using QSortFilterProxyModel. The reason for that is that this class only filters elements - menas it hides (or not) some elements, basing on given criteria. What you want to do is restructuring tree into new one (having choosen elements from arbitary position at root-children). This is only possible by creating your own QProxyModel descendant and implementing yourself tree-rebuilding, and mapping indexes between old and new tree.

Describing exactly how to do this is a bit long for an answer here.

like image 23
j_kubik Avatar answered Oct 16 '22 19:10

j_kubik