在 QFileDialog 中过滤 [英] Filtering in QFileDialog
问题描述
我想更具体地过滤 QFileDialog
中显示的文件,而不仅仅是通过文件扩展名.我在 Qt 文档中找到的示例仅显示过滤器,例如 Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)
和这样的.除此之外,我还想为不出现在文件对话框中的文件指定一个过滤器,例如XML 文件 (*.xml)
但不是 备份 XML 文件 (*.backup.xml)
.
I would like to filter the files that are shown in a QFileDialog
more specifically than just by file extensions. The examples I found in the Qt documentation only show filters like Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)
and such. In addition to this I would also like to specify a filter for files that should not show up in the file dialog, e.g. XML files (*.xml)
but not Backup XML files (*.backup.xml)
.
所以我的问题是我想在文件对话框中显示一些具有特定文件扩展名的文件,但我不想显示具有特定文件名后缀(和相同文件扩展名)的其他文件.
So the problem I have is that I would like to show some files in the file dialog that have certain file extension, but I would not like to show other files with a specific file name suffix (and the same file extension).
例如:
要显示的文件:
file1.xml
file2.xml
不显示的文件:
file1.backup.xml
file2.backup.xml
我想问一下是否可以为 QFileDialog
定义这样的过滤器?
I would like to ask if it is possible to define filters like these for a QFileDialog
?
推荐答案
我相信你能做的是:
- 创建自定义代理模型.您可以使用 QSortFilterProxyModel 作为模型的基类;
- 在代理模型中覆盖 filterAcceptsRow 方法并返回 false用于名称中包含 .backup." 字样的文件;
- 为文件对话框设置新的代理模型:QFileDialog::setProxyModel一个>;
- Create a custom proxy model. You can use QSortFilterProxyModel as a base class for your model;
- In the proxy model override the filterAcceptsRow method and return false for files which have the ".backup." word in their names;
- Set new proxy model to the file dialog: 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.setOption(QFileDialog::DontUseNativeDialog);
dialog.setProxyModel(new FileFilterProxyModel);
dialog.setNameFilter("XML (*.xml)");
dialog.exec();
仅非本机文件对话框支持代理模型.
The proxy model is supported by non-native file dialogs only.
这篇关于在 QFileDialog 中过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!