qt 扫描文件夹中的文件_qt中显示文件夹下的目录及文件的过滤

本文介绍了两种在QT中扫描文件夹并显示特定类型文件的方法。第一种是通过QDirModel和QSortFilterProxyModel的子类,自定义过滤规则只显示.cpp和.h文件。第二种方法直接使用QFileSystemModel,设置名称过滤器来实现相同功能。示例代码展示了如何在QT界面中展示D:/program目录下的目录和.cpp、.h文件。
摘要由CSDN通过智能技术生成

第一种方法:QDirModel + QSortFilterProxyModel的子类

写一个类,继承QSortFilterProxyModel,重写filterAcceptsRow方法

mysortfilter.h文件代码

#ifndef MYSORTFILTER_H

#define MYSORTFILTER_H

#include

#include

class mySortFilter : public QSortFilterProxyModel

{

public:

mySortFilter();

~mySortFilter();

protected:

bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;

};

#endif // MYSORTFILTER_H

mysortfilter.cpp文件

#include "mysortfilter.h"

#include

#include

mySortFilter::mySortFilter()

{

}

mySortFilter::~mySortFilter()

{

}

bool mySortFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const

{

if(!sourceModel()) return false;

QModelIndex index = sourceModel()->index(source_row, 0, source_parent);

QDirModel *model = static_cast(sourceModel());

QString str = model->fileName(index);

if (model->fileInfo(index).isDir()) return true;

else if (model->fileInfo(index).isFile() && (str.endsWith(".cpp") || (str.endsWith(".h")))) return true;

return false;

}

mainwindow.cpp 文件

#include "mainwindow.h"

#include "ui_mainwindow.h"

#include

#include "mysortfilter.h"

MainWindow::MainWindow(QWidget *parent) :

QMainWindow(parent),

ui(new Ui::MainWindow)

{

ui->setupUi(this);

QDirModel *model = new QDirModel();

mySortFilter *proxyModel = new mySortFilter();

proxyModel->setSourceModel(model);

ui->treeView->setModel(proxyModel);

ui->treeView->setRootIndex(proxyModel->mapFromSource(model->index("D:/program")));

}

MainWindow::~MainWindow()

{

delete ui;

}

输出结果

第二种方法:QFileSystemModel

如果用QDirModel实现这有些困难,并且QDirModel在qt新版本中是不推荐使用。可以用QFileSystemModel,只需要调用其成员函数setNameFilters就可以,如实现显示文件下D:/program文件下的目录及.cpp和.h文件

QFileSystemModel *model = new QFileSystemModel();

model->setRootPath("d:/");

QStringList nameFilter;

nameFilter << "*.cpp" << "*.h";

model->setNameFilterDisables(false);

model->setNameFilters(nameFilter);

ui->treeView->setModel(model);

ui->treeView->setRootIndex(model->index("D:/program"));

运行结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值