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

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

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

mysortfilter.h文件代码

#ifndef MYSORTFILTER_H
#define MYSORTFILTER_H

#include <QObject>
#include <QSortFilterProxyModel>

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 <QDirModel>
#include <QtDebug>

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<QDirModel*>(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 <QDirModel>
#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"));

运行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值