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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With