隐藏那些没有过滤文件的文件夹

时间:2013-10-03 11:23:35

标签: c++ qt qtreeview qfilesystemmodel qsortfilterproxymodel

我正在开发QTreeviews,其中包含所有驱动器。另一个显示与这些驱动器对应的所有文件和文件夹。我已经为某些特定文件应用了过滤器。因此,它显示所有具有这些特定过滤器格式的文件夹以及那些没有过滤文件作为空文件夹的文件夹。现在我的问题是,我不想显示那些没有我的过滤文件的文件夹。我正在使用这个:

QFileSystemModel *fileSystemModel = new QFileSystemModel(this);
fileSystemModel->setRootPath(path);
QStringList filters;
filters <<"*.jpeg" <<"*.pict" <<"*.PICT" <<"*.xpm" <<"*.xbm" <<"*.ppm" <<"*.pbm" <<"*.pgm" <<"*.XBM" <<"*.XPM" <<"*.PPM" <<"*.PBM" <<"*.PGM" <<"*.png" <<"*.psd" <<"*.bmp"<<"*.jp2" <<"*.tiff" <<"*.gif" <<"*.tga" <<"*.jpg" <<"*.JPG" <<"*.JPEG" <<"*.BMP" <<"*.JP2"<<"*.PSD" <<"*.PNG" <<"*.TIFF" <<"*.GIF" <<"*.TGA"  ;
fileSystemModel->setNameFilters(filters);
fileSystemModel->setNameFilterDisables(0);
fileSystemModel->setSupportedDragActions(Qt::CopyAction);
fileSystemModel->fetchMore(fileSystemModel->index(path));
ui->treeView_2->setModel(fileSystemModel);
ui->treeView_2->setRootIndex(fileSystemModel->index(path));
ui->treeView_2->setColumnWidth(0,300);

任何人都可以帮助我。 感谢。

2 个答案:

答案 0 :(得分:0)

我这样做是为了创建我的Qfilesystemmodel:

QFileSystemModel *fileSystemModel = new QFileSystemModel(this);
fileSystemModel->setRootPath(path);
QStringList filters;
filters <<"*.jpeg" <<"*.pict" <<"*.PICT";
fileSystemModel->setNameFilters(filters);
fileSystemModel->setNameFilterDisables(0);
ui->treeView_2->setModel(fileSystemModel);
ui->treeView_2->setRootIndex(fileSystemModel->index(path));
ui->treeView_2->setColumnWidth(0,300);                          
connect(fileSystemModel,SIGNAL(directoryLoaded(QString)),this,SLOT(onDirLoaded(QString)));


void MainWindow::onDirLoaded(QString path)
{

QFileSystemModel *fileSystemModel=(QFileSystemModel*)ui->treeView_2->model();
QModelIndex index = fileSystemModel->index(path);
QStringList filters;

filters <<"*.jpeg" <<"*.pict" <<"*.PICT";
fileSystemModel->setNameFilters(filters);
fileSystemModel->setNameFilterDisables(0);
int rowCount = fileSystemModel->rowCount(index);
for(int i=0;i<rowCount;i++)
{
    QModelIndex mi = fileSystemModel->index(i,0,index);
    QFileInfo fileInfo = fileSystemModel->fileInfo(mi);
    if (!templist.contains(fileInfo.absoluteFilePath()))
    {
        templist << fileInfo.absoluteFilePath();
        tempNamelist << fileInfo.fileName();
    }
    if(!bloaded)
    {
        if(fileSystemModel->hasChildren(mi))
        {
            QModelIndex index1 = fileSystemModel->index(i,0,index);
            int rowCount1 = fileSystemModel->rowCount(index1);
            if(rowCount1)
            {
                onDirLoaded(fileInfo.absoluteFilePath());
            }
        }
    }
 }


}

使用这个我能够创建Qfilsystemmodel,但它也显示那些没有过滤文件的子文件夹。我不想显示那些子文件夹。你的帮助会非常感激。

谢谢,

答案 1 :(得分:-1)

查看documentation of QSortFilterProxyModel

您可以检查文件夹是否包含任何内容,然后决定是否应该从结果中筛选出来。