将QSortFilterProxyModel与树模型一起使用 [英] Using QSortFilterProxyModel with a tree model

查看:88
本文介绍了将QSortFilterProxyModel与树模型一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个QDirModel,其当前目录已设置.然后,我有一个QListView,它应该显示该目录中的文件.效果很好.

I have a QDirModel whose current directory is set. Then I have a QListView which is supposed to show the files in that directory. This works fine.

现在,我想限制显示的文件,因此它仅显示 png 个文件(文件名以.png结尾).问题是使用QSortFilterProxyModel并设置过滤器regexp也会尝试匹配文件的每个父项.根据文档:

Now I want to limit the files shown, so it only shows png files (the filename ends with .png). The problem is that using a QSortFilterProxyModel and setting the filter regexp will try to match every parent of the files as well. According to the documentation:

对于分层模型,过滤器为 递归地应用于所有孩子. 如果父项不匹配 过滤器,它的所有子项都不会 显示.

For hierarchical models, the filter is applied recursively to all children. If a parent item doesn't match the filter, none of its children will be shown.

那么,如何获取QSortFilterProxyModel仅过滤目录中的文件,而不过滤其驻留的目录?

So, how do I get the QSortFilterProxyModel to only filter the files in the directory, and not the directories it resides in?

推荐答案

对于像我这样对以下行为感兴趣的人:如果孩子匹配过滤器,则不应隐藏其祖先:

For people like me who are interested in the following behaviour : if a child matches the filter, then its ancestors should not be hidden :

bool MySortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex & source_parent) const
{
    // custom behaviour :
    if(filterRegExp().isEmpty()==false)
    {
        // get source-model index for current row
        QModelIndex source_index = sourceModel()->index(source_row, this->filterKeyColumn(), source_parent) ;
        if(source_index.isValid())
        {
            // if any of children matches the filter, then current index matches the filter as well
            int i, nb = sourceModel()->rowCount(source_index) ;
            for(i=0; i<nb; ++i)
            {
                if(filterAcceptsRow(i, source_index))
                {
                    return true ;
                }
            }
            // check current index itself :
            QString key = sourceModel()->data(source_index, filterRole()).toString();
            return key.contains(filterRegExp()) ;
        }
    }
    // parent call for initial behaviour
    return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent) ;
}

这篇关于将QSortFilterProxyModel与树模型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆