【问题标题】:Hide items of a QFileSystemModel/QTreeView via indexes using a specific rule使用特定规则通过索引隐藏 QFileSystemModel/QTreeView 的项目
【发布时间】:2019-04-07 22:09:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ qt qtreeview qfilesystemmodel qsortfilterproxymodel


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!它有效,但每次更改条件时过滤器都不会更新。就我而言,应该隐藏的项目存储在列表中。您知道如何在更新列表时自动更新过滤器吗?
    • 算了,我刚刚想通了。我只需要在更改条件时发出 sourceModel()->dataChanged() 。再次感谢您!
    • 您也可以拨打QSortFilterProxyModel::invalidateFilter()更改您的过滤器参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多