Search code examples
qtqt-creatorqfiledialog

How specify file filter in QFileDialog::getExistingDirectory?


I need to choose a directory with files "*.in". But if i use getExistingDirectory, i can't specify file filter, so i can't see files.

But i need to see ONLY "*.in" files, i could be only choose a directory, not a file. Now i use this code:

qDebug() << QFileDialog::getExistingDirectory(this, tr("Выберите папку с файлами устройств"), "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

And i can't see any files in chosen directory (in dialog).

How i can do this?


Solution

  • You need to pass QFileDialog::DontUseNativeDialog option. From the documentation of getExistingDirectory:

    On Windows and OS X, this static function will use the native file dialog and not a QFileDialog. However, the native Windows file dialog does not support displaying files in the directory chooser. You need to pass DontUseNativeDialog to display files using a QFileDialog. On Windows CE, if the device has no native file dialog, a QFileDialog will be used.

    To filter displayed files by extension you will have to do slightly more:

    QFileDialog dlg(nullptr, tr("Choose Directory"));
    dlg.setOptions(QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    dlg.setFileMode(QFileDialog::Directory);
    dlg.setNameFilter(tr("Directories with device files (*.in)"));
    if (dlg.exec())
        qDebug() << dlg.selectedFiles();
    

    When I tried this, the files that don't match the filter were still displayed, but in grey color (I tried on MacOS, maybe you will have more luck on Windows).

    There is no standard way to prevent user from selecting a folder which contains no files matching the filter. A solution is to derive your own class from QFileDialog and override the accept function (not calling QFileDialog::accept from your override will prevent the dialog from closing).