自定义高级QFileDialog文件过滤器

时间:2022-12-03 21:39:44

QFileDialog提供了一个函数---setproxyModel。。就是用这个来玩了。就是override filterAcceptsRow的虚函数,里面定制自己的过滤需求。返回bool   下面就是判断是否是目录,只显示目录文件夹。

 #ifndef PROXY_MODEL_H
#define PROXY_MODEL_H #include <QSortFilterProxyModel> class FileFilterProxyModel : public QSortFilterProxyModel
{
public:
FileFilterProxyModel(QObject* parent) :QSortFilterProxyModel(parent){} protected:
virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
}; #endif
#include "proxymodel.h"

#include <QFileSystemModel>
#include <QDebug> bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel()); if (fileModel != NULL && fileModel->isDir(index0))
{
qDebug() << fileModel->fileName(index0);
return true;
}
else
return false;
// uncomment to execute default implementation
//return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}

  

 QFileDialog dialog;
FileFilterProxyModel* proxyModel = new FileFilterProxyModel();
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.setProxyModel(proxyModel);
dialog.exec();

references:

http://*.com/questions/4893122/filtering-in-qfiledialog

http://*.com/questions/2101100/qfiledialog-filtering-folders