Regular Expression Filter for QFileDialog

I would like to display a file open dialog that filters a specific template, for example *.000- *.999.

QFileDialog::getOpenFileNamesallows you to specify discrete filters, such as *.000, *.001etc. I would like to set the regular expression as a filter, in this case ^.*\.\d\d\d$, that is, any file name that has a three-digit extension.

0
source share
2 answers

ariwez pointed me in the right direction. The main thing you need to pay attention to is call dialog.setOption(QFileDialog::DontUseNativeDialog)up dialog.setProxyModel.

Proxy Model:

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 box is created as follows:

QFileDialog dialog;

// Call setOption before setProxyModel.
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.setProxyModel(new FileFilterProxyModel);
dialog.exec();
0
source

, - QFileDialog. : QFileDialog

+1

All Articles