Search code examples
c++qtqfiledialog

Selecting files with folder using QFileDialog


I have a use case in an application using C++ and Qt (on windows 10). The application uses 7zip.exe as a subprocess to uncompress the files in a selected folder. I need to use QFileDialog to select a folder, and get all the files with extension .zip and .7z, to be selected automatically and then uncompress them using QProcess and display them in the output. I came up with this code snippet. For selecting the files with selected folders.

void MainWindow::on_browseButton_clicked()
{
      QFileDialog d(this);
      d.setFileMode(QFileDialog::Directory);
      d.setNameFilter("*.zip");
      if (d.exec())
        qDebug () << d.selectedFiles();
}

but this code does not run, and it displays just the folder name not with no files selected. Could anyone suggest where I am doing wrong.

enter image description here


Solution

  • it displays just the folder name not with no files selected.

    That is what it is supposed to return. You asked it to display a dialog to select a folder, so that is all you can select. selectedFiles() will return the path to the selected folder, per the documentation:

    https://doc.qt.io/qt-5/qfiledialog.html#FileMode-enum

    Constant Value Description
    QFileDialog::Directory 2 The name of a directory. Both files and directories are displayed. However, the native Windows file dialog does not support displaying files in the directory chooser.

    https://doc.qt.io/qt-5/qfiledialog.html#selectedFiles

    Returns a list of strings containing the absolute paths of the selected files in the dialog. If no files are selected, or the mode is not ExistingFiles or ExistingFile, selectedFiles() contains the current path in the viewport.

    After the dialog has closed and exec() has returned, you will then need to iterate that folder yourself to discover .zip and .7z files in it.

    An easier way to handle the dialog is to use QFileDialog::getExistingDirectory() instead. You can construct a QDir from the selected folder, and then use the QDir::entryList() method to search for zip files in the folder.

    See How to read all files from a selected directory and use them one by one?.

    For example:

    void MainWindow::on_browseButton_clicked()
    {
        QDir directory = QFileDialog::getExistingDirectory(this);
        QStringList zipFiles = directory.entryList(QStringList() << "*.zip" << "*.7z", QDir::Files);
        foreach(QString filename, zipFiles) {
            // do whatever you need to do
        }
    }