开发者

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

开发者 https://www.devze.com 2023-04-07 14:40 出处:网络
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 fo

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.


Of course setRootIndex is the solution for this case, but if you will be looking for more complicated model manipulations you may consider using custom proxy models like http://lynxline.com/category/models/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号