Filtering in QFileDialog

一曲冷凌霜 提交于 2019-11-28 01:17:55
serge_gubenko

I believe what you can do is:

  1. Create a custom proxy model. You can use QSortFilterProxyModel as a base class for your model;
  2. In the proxy model override the filterAcceptsRow method and return false for files which have the ".backup." word in their names;
  3. Set new proxy model to the file dialog: QFileDialog::setProxyModel;

Below is an example:

Proxy model:

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);
}

dialog was created this way:

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

The proxy model is supported by non-native file dialogs only.

The solution of @serge_gubenko is working well. Create your own ProxyModel by inheriting from the QSortFilterProxyModel.

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;
}

Just make sure to set DontUseNativeDialog before setting the Proxy model (not the way that @serge_gubenko did it). Native dialogs do not support custom ProxyModels.

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

It took quite some time for me to find this out. This was written here

White Hat Hacker

Okay, I've used it with QFileDialog object. And this only shows me the files listed in the appropriate directory. It is excellent to just choose the files to be processed. For example, an XML file, a PNG image, etcetera.

Here I present my example

 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; 

The dialog box will display only presents xml files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!