使用特定规则通过索引隐藏QFileSystemModel / QTreeView的项目

问题描述 投票:0回答:1

我正在使用QTreeView + QFileSystemModel在我的Qt程序中显示文件夹的内容。

现在我想隐藏该视图的特定项目。显示规则不基于文件名,因此我不能使用setNameFilters()。我所拥有的是一个简单的QModelIndex列表,其中包含我要隐藏的所有项目。有没有一种方法只使用此列表过滤视图?

在我的研究中,我遇到了QSortFilterProxyModel类,但我无法想象如何使用它来实现我想要的。任何帮助,将不胜感激。

c++ qt qtreeview qfilesystemmodel qsortfilterproxymodel
1个回答
0
投票

子类QSortFilterProxyModel并覆盖方法filterAcceptsRow来设置过滤器逻辑。

例如,要过滤当前用户的写入权限:

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.