Filtering in QFileDialog

前端 未结 3 850
忘掉有多难
忘掉有多难 2020-12-06 19:05

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 on

3条回答
  •  误落风尘
    2020-12-06 19:52

    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(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.setOption(QFileDialog::DontUseNativeDialog);
    dialog.setProxyModel(new FileFilterProxyModel);
    dialog.setNameFilter("XML (*.xml)");
    dialog.exec();
    

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

提交回复
热议问题