自定义高级QFileDialog文件过滤器

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

 1 #ifndef PROXY_MODEL_H
 2 #define PROXY_MODEL_H
 3 
 4 #include <QSortFilterProxyModel>
 5 
 6 
 7 class FileFilterProxyModel : public QSortFilterProxyModel
 8 {
 9 public:
10     FileFilterProxyModel(QObject* parent) :QSortFilterProxyModel(parent){}
11 
12 protected:
13     virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
14 };
15 
16 
17 #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);
}

  

 

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

 

 

 

 

 

references:

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

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

posted @ 2015-06-19 11:23  foo__hack  阅读(3653)  评论(0编辑  收藏  举报