第一种方法: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"));
运行结果: