Qt4 TreeView – Items Filtering

August 30, 2008 Matteo Bertozzi | Filed Under Qt4 | 1 Comment

In 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));
  }
};
Qt4 Filtered TreeView

Qt4 Filtered TreeView

Here you can find the example source code: http://th30z.netsons.org/wp-content/uploads/qfilteredtreeview.cpp

1 Comment »

RSS feed for comments on this post. TrackBack URI

  1. 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 #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>