How can I implement my own proxy model that is more advanced than just sorting/filtering

In cases such as being able to hide the top level items but yet still see the children in an itemview is where you would want to use a proxy model. However QSortFilterProxyModel by itself is not adequate enough for the functionality needed.

Therefore you need to subclass QAbstractProxyModel instead which enables you to have full control over the way that the proxy model represents the items from the source model.

Attached to this solution is an example which shows how to handle this for a case where you want to hide all items except for the children (and grandchildren) of a particular item. Since we want to hide a top level item here, we need to actually ensure that the proxy items end up with new parents since the hierarchy has changed.

To do this in a way that makes it easy to manipulate the hierarchy in any way you want we have created two maps, one for the mapping of a source index to its corresponding proxy index. The other map is for mapping a proxy index to its new parent as represented by the original source index.

The reason behind mapping a proxy index to a parent index in the source model is to facilitate placing proxy indexes whereever we want them to be without having to be concerned with not having mapped the corresponding source index yet. Therefore we can easily map a child of an index in the source model to be the parent of that index in the proxy model.

The example uses QStandardItemModel to simplify things on the source model side, but you can change the model in use on the source model and just tweak the fixModel() function to handle your own model instead.

4 comments

August 6, 2010

Picture of mariusg mariusg

Ant Farmer

Attachment is missing so I’ve put it in the wiki here [developer.qt.nokia.com].

March 14, 2011

Picture of surana4u surana4u

Lab Rat

If I remove

  1. !si->text().startsWith("A")
then also output is same. It is not showing other child items.

April 12, 2011

Picture of surana4u surana4u

Lab Rat

People interested in achieving this task(hide all items except for the children) may also like to look at this blog entry http://lynxline.com/jongling-qt-models/

May 11, 2011

Picture of AndyS AndyS

Lab Rat

The example has been updated now to show more of a reason behind why the

  1. !si->text().startsWith("A")

check is there because it is really to show for demonstration purposes.

Write a comment

Sorry, you must be logged in to post a comment.