Filter Columns in a QFileSystemModel

From Qt Wiki
Revision as of 09:54, 24 February 2015 by Maintenance script (talk | contribs)
Jump to: navigation, search

How to Filter Columns in a QFileSystemModel

Sometimes one does not want to display all the columns of a "QFileSystemModel":, like discussed in "this forum thread":

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 <code&gt;QHeaderView&lt;/code&gt;, but the alternative to subclass "QSortFilterProxyModel&quot;: and reimplement the <code&gt;filterAcceptsColumn()</code&gt; method also works well.

Column hiding using QHeaderView

All multi-column views provide access to a "QHeaderView&quot;: . 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.

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

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.


#include <QSortFilterProxyModel&gt;

class FSMProxy : public QSortFilterProxyModel

FSMProxy(QObject *parent);

bool filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const;


FSMProxy::FSMProxy(QObject *parent)
 : QSortFilterProxyModel(parent)

bool FSMProxy::filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const

    // adjust the columns you want to filter out here
    // return false for those that will be hidden
if(source_column 2 || source_column 3)
return false;
return true;


    QFileSystemModel *fsm = new QFileSystemModel(this);
    FSMProxy *proxy = new FSMProxy(this);