我有一个设置了当前目录的QDirModel。然后我有一个QListView,它应该显示目录中的文件。这个很好用。
现在我想限制显示的文件,所以它只显示png文件(文件名以.png结尾)。问题是,使用QSortFilterProxyModel并设置筛选器regexp也会尝试匹配文件的每个父级。根据文件:
对于分层模型,过滤器被递归地应用于所有子模型。如果父项与筛选器不匹配,则不会显示其子项。
那么,如何使QSortFilterProxyModel只过滤目录中的文件,而不是它所在的目录?
发布于 2012-06-06 09:45:04
对于像我这样对以下行为感兴趣的人:如果一个孩子与过滤器匹配,那么它的祖先就不应该被隐藏起来:
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) ;
}发布于 2019-03-07 18:41:45
从QT5.10开始,QSortFilterProxyModel可以选择递归过滤。换句话说,如果一个孩子与过滤器匹配,那么它的父母也是可见的。
发布于 2008-10-31 15:41:08
我们在我工作的地方遇到了类似的情况,最后我们创建了自己的代理模型来进行过滤。但是,在文档中查找您想要的内容(这似乎是一个更常见的情况),我遇到了两种可能性。
filterAcceptsRow函数。从文件中:可以通过重新实现filterAcceptsRow()和filterAcceptsColumn()函数来实现自定义过滤行为。
然后,您大概可以使用模型索引来检查索引项是目录(自动接受)还是文件(文件名上的筛选器)。
https://stackoverflow.com/questions/250890
复制相似问题