Qt4 TreeView – Items Filtering
August 30, 2008 Matteo Bertozzi | Filed Under Qt4 | 1 CommentIn a few words, I’ve a QTreeView that displays folder items. I Need to filter items, showing empty folders.
QSortFilterProxyModel: For hierarchical models, the filter is applied recursively to all children. If a parent item doesn’t match the filter, none of its children will be shown.
Using QSortFilterProxyModel the result is that the filter is applied on the foldes, so we’ve something like a root only filter. The solution is simple.. Inherits QSortFilterProxyModel and…
class QfTreeProxyModel : public QSortFilterProxyModel {
public:
QfTreeProxyModel (QObject *parent = 0)
: QSortFilterProxyModel(parent)
{
setFilterCaseSensitivity(Qt::CaseInsensitive);
}
protected:
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex idx = sourceModel()->index(source_row, 0, source_parent);
if (sourceModel()->hasChildren(idx))
return(true);
return(QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent));
}
};
Here you can find the example source code: http://th30z.netsons.org/wp-content/uploads/qfilteredtreeview.cpp

That is a neat solution, however a folder item will still be shown, even if it doesn’t have any filter-matching children.
Comment by Casey — October 26, 2009 #