How to open the file explorer in Qt?

In Qt, you can use the QFileDialog class to open the file explorer. Below is an example code demonstrating how to open the file explorer and select a file or folder.

#include <QApplication>
#include <QFileDialog>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 打开文件资源管理器并选择文件
    QString filePath = QFileDialog::getOpenFileName(nullptr, "选择文件", "", "所有文件 (*.*)");

    // 打开文件资源管理器并选择文件夹
    QString dirPath = QFileDialog::getExistingDirectory(nullptr, "选择文件夹", "");

    return a.exec();
}

The code above, the function getOpenFileName is used to select a file, while the function getExistingDirectory is used to select a folder. The first parameter is the pointer to the parent window, which can be set to nullptr, the second parameter is the title of the dialog, the third parameter is the default path displayed when opening the dialog, and the fourth parameter is the file filter which can be set as needed.

After running the above code, a file explorer dialog will appear, allowing you to choose a file or folder. Once selected, the corresponding path will be stored in the variables filePath or dirPath.

bannerAds