简体   繁体   中英

Hide items of a QFileSystemModel/QTreeView via indexes using a specific rule

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM