Regular Expression Filter for QFileDialog

懵懂的女人 提交于 2019-12-02 10:14:53
ariwez

It can be done by adding proxy model to QFileDialog. It is explained here: Filtering in QFileDialog

ariwez pointed me into the right direction. The main thing to watch out for is to call dialog.setOption(QFileDialog::DontUseNativeDialog) before dialog.setProxyModel.

The proxy model is:

class FileFilterProxyModel : public QSortFilterProxyModel
{
protected:
    virtual bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
    {
        QModelIndex index0 = sourceModel()->index(sourceRow, 0, sourceParent);
        QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());

        // I don't want to apply the filter on directories.
        if (fileModel == nullptr || fileModel->isDir(index0))
            return true;

        auto fn = fileModel->fileName(index0);

        QRegExp rx(".*\\.\\d\\d\\d");
        return rx.exactMatch(fn);
    }
};

The file dialog is created as follows:

QFileDialog dialog;

// Call setOption before setProxyModel.
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.setProxyModel(new FileFilterProxyModel);
dialog.exec();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!