0

I'm displaying the contents of a folder in my Qt program using a QTreeView + QFileSystemModel.

Now I want to hide specific items of that view. The display rule is not based on the file names, so I can't use setNameFilters(). What I have is a simple list of QModelIndex containing all the items I want to hide. Is there a way of filtering the view using only this list?

In my research I came across the QSortFilterProxyModel class, but I couldn't figure how to use it in order to achieve what I want. Any help would be appreciated.

1 Answers1

0

Subclass QSortFilterProxyModel and override the method filterAcceptsRow to set the filter logic.

For example, to filter on current user write permissions :

class PermissionsFilterProxy: public QSortFilterProxyModel
{
public:
    PermissionsFilterProxy(QObject* parent=nullptr): QSortFilterProxyModel(parent)
    {}

    bool filterAcceptsRow(int sourceRow,
            const QModelIndex &sourceParent) const
    {
        QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
        QFileDevice::Permissions permissions = static_cast<QFileDevice::Permissions>(index.data(QFileSystemModel::FilePermissions).toInt());
        return permissions.testFlag(QFileDevice::WriteUser); // Ok if user can write
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QFileSystemModel* model = new QFileSystemModel();
    model->setRootPath(".");

    QTreeView* view = new QTreeView();
    PermissionsFilterProxy* proxy = new PermissionsFilterProxy();
    proxy->setSourceModel(model);
    view->setModel(proxy);
    view->show();
    return app.exec();
}
Dimitry Ernot
  • 6,256
  • 2
  • 25
  • 37
  • Thank you very much! It works, but the filter is not updated every time I change the conditions. In my case, the items supposed to be hidden are stored in a list. Do you know how can I update the filters automatically when I update the list? – Pericles Carvalho Apr 08 '19 at 01:13
  • Forget about it, I just figured out. I just had to emit sourceModel()->dataChanged() when changing the conditions. Once again, thank you very much! – Pericles Carvalho Apr 08 '19 at 02:39
  • You can also call `QSortFilterProxyModel::invalidateFilter()` when you want to change your filter parameters. – Dimitry Ernot Apr 08 '19 at 07:08