How to Filter Columns in a QFileSystemModel

Sometimes one does not want to display all the columns of a QFileSystemModel [doc.qt.nokia.com], like discussed in this forum thread [developer.qt.nokia.com].

This can be achieved in two ways, either by hiding the columns in the view, by using a specialized proxy model. The easiest way is to hide the columns using the QHeaderView, but the alternative to subclass QSortFilterProxyModel [doc.qt.nokia.com] and reimplement the filterAcceptsColumn() method also works well.

Column hiding using QHeaderView

All multi-column views provide access to a QHeaderView [doc.qt.nokia.com] . This is the widget that provides the headers above the columns of data, and allows the user to resize those columns, or click the headers to trigger a sorting order. You can also use this widget to hide columns in your view.

  1. //hide the third and fourth column, note that the column numbers are 0-based
  2. QHeaderView* hHeader = m_theTableview->horizontalHeader();
  3. hHeader->hideSection(2);
  4. hHeader->hideSection(3);

The alternative method of using a custom proxy model is outlined below.

Column hiding using QSortFilterProxyModel

Be aware that the column count is 0-based and that it is hard coded.

fsmproxy.h
  1. #include <QSortFilterProxyModel>
  2.  
  3. class FSMProxy : public QSortFilterProxyModel
  4. {
  5.     Q_OBJECT
  6.  
  7. public:
  8.     FSMProxy(QObject *parent);
  9.  
  10. protected:
  11.     bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const;
  12. };

fsmproxy.cpp
  1. FSMProxy::FSMProxy(QObject *parent)
  2.     : QSortFilterProxyModel(parent)
  3. {
  4. }
  5.  
  6.  
  7. bool FSMProxy::filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const
  8. {
  9.     Q_UNUSED(source_parent)
  10.  
  11.     // adjust the columns you want to filter out here
  12.     // return false for those that will be hidden
  13.     if(source_column == 2 || source_column == 3)
  14.         return false;
  15.     return true;
  16. }

Usage
  1.     QFileSystemModel *fsm = new QFileSystemModel(this);
  2.     FSMProxy *proxy = new FSMProxy(this);
  3.     proxy->setSourceModel(fsm);
  4.     treeView->setModel(proxy);

Categories: