2011-02-03 102 views
5

我想过滤QFileDialog中显示的文件,而不仅仅是文件扩展名。我在Qt文档中找到的示例仅显示诸如Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)之类的过滤器等。除此之外,我还希望为文件指定一个过滤器,以便在文件对话框中显示而非,例如, XML files (*.xml)但不是Backup XML files (*.backup.xml)在QFileDialog中过滤

所以我的问题是我想在文件对话框中显示某些文件具有某些文件扩展名,但我不想显示具有特定文件名后缀的其他文件(以及相同的文件扩展名) 。

例如:

文件显示:

file1.xml 
file2.xml 

文件未显示:

file1.backup.xml 
file2.backup.xml 

我想问一下,如果它可以定义这样的一个过滤器QFileDialog

回答

9

我相信你可以做的是:

  1. 创建自定义代理模型。您可以使用QSortFilterProxyModel作为您的模型的基类;
  2. 在代理模型中,覆盖filterAcceptsRow方法,并为具有“.backup”的文件返回false。单词在他们的名字;
  3. 将新代理模型设置为文件对话框:QFileDialog::setProxyModel;

下面是一个例子:

代理模式:

class FileFilterProxyModel : public QSortFilterProxyModel 
{ 
protected: 
    virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; 
}; 

bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const 
{ 
    QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent); 
    QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel()); 
    return fileModel->fileName(index0).indexOf(".backup.") < 0; 
    // uncomment to call the default implementation 
    //return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); 
} 

对话框创建这样:

QFileDialog dialog; 
dialog.setProxyModel(new FileFilterProxyModel); 
dialog.setNameFilter("XML (*.xml)"); 
dialog.setOption(QFileDialog::DontUseNativeDialog); 
dialog.exec(); 

代理模型仅由非本地文件对话框支持。

0

好吧,我用它与QFileDialog对象。这只显示了相应目录中列出的文件。选择要处理的文件非常好。例如,一个XML文件,一个PNG图像等等。

在这里,我提出我的例子

OlFileDialog QFileDialog (this); 
QString slFileName; 
olFileDialog.setNameFilter (tr ("Files (* xml)")); 
olFileDialog.setFileMode (QFileDialog :: anyfile); 
olFileDialog.setViewMode (QFileDialog :: Detail); 
if (olFileDialog.exec()) 
    olFileDialog.selectFile (slFileName); 
else 
    return; 

该对话框将只显示呈现的XML文件。

0

@serge_gubenko的解决方案运行良好。通过继承QSortFilterProxyModel创建您自己的ProxyModel

class FileFilterProxyModel : public QSortFilterProxyModel 
{ 
protected: 
    virtual bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; 
}; 

bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const 
{ 
    // Your custom acceptance condition 
    return true; 
} 

只要确保设置前DontUseNativeDialog设置代理模型(不是@serge_gubenko所采取的方式)。本机对话框不支持自定义ProxyModel s。

QFileDialog dialog; 
dialog.setOption(QFileDialog::DontUseNativeDialog); 
dialog.setProxyModel(new FileFilterProxyModel); 
dialog.setNameFilter("XML (*.xml)"); 
dialog.exec(); 

我花了相当一段时间才发现这一点。这写的here

+0

这不提供问题的答案。一旦你有足够的[声誉](https://stackoverflow.com/help/whats-reputation),你将可以[对任何帖子发表评论](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提问者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [来自评论](/ review/low-quality-posts/18085257) – 2017-11-28 10:32:40