New in Qt 5.10: recursive filtering for QSortFilterProxyModel
When using Qt’s model/view framework, filtering has always been very easy with QSortFilterProxyModel. To filter a list using text typed by the user in a line-edit, you have certainly been applying the standard recipe:
- instantiate the proxy;
- insert it between view and source model;
- connect the lineedit’s
textChangedsignal to the proxy’s
But what if the model is a tree rather than a flat list?
Let’s use the tree below as an example. As you can see by looking at the highlighted row, there is a toplevel item “Form Editing Mode” containing the item “Layouts”, which itself contains an item with the word “Vertical”.
Now if we use the same code for filtering as for a flat model, we get a rather unpleasant surprise: typing “Vertical” shows… an empty view.
This is because the toplevel item “Form Editing Mode” doesn’t match the filter and therefore it has been filtered out, with no consideration for its children.
This is logical from an implementation point of view (
filterAcceptsRow() returns false, the whole subtree is filtered out), but this isn’t what we wanted to achieve.
Introducing recursive filtering
We need the parents of matching items to be considered as matching the filter too. Until now this wasn’t easily possible.
This is the reason why I implemented (with the help of my colleague Filipe Azevedo) a “recursive filtering” feature in QSortFilterProxyModel. It has just been merged into Qt’s dev branch (commit), which means it will be in Qt 5.10. You will need to be a bit patient, but at some point you will be able to make filtering work for tree models by adding one simple line of code:
And here’s the result:
Pretty neat, isn’t it?
KDAB believes that it is critical for our business to contribute to the Qt framework and C++ thinking, to keep pushing these technologies forward to ensure they remain competitive.