Saturday, August 30, 2008

Qt4 TreeView - Items Filtering

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 {
    QfTreeProxyModel (QObject *parent = 0)
      : QSortFilterProxyModel(parent)

    bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
      QModelIndex idx = sourceModel()->index(source_row, 0, source_parent);
      if (sourceModel()->hasChildren(idx))
      return(QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent));

Here you can find the example source code:

1 comment:

  1. That is a neat solution, however a folder item will still be shown, even if it doesn't have any filter-matching children.