Qt 打开指定路径的目录

发布时间 2023-10-30 17:17:54作者: Jeffxue

有些操作需要打开指定路径的目录,此时可以使用 QDesktopServices::openUrl(const QUrl &url)函数来实现。

#include <QDesktopServices>

void OpenFolder()
{
    QString folderPath = "C:\\tmp\\TargetFile";
    QString finalPath = "file:///" + folderPath;
    QDesktopServices::openUrl(QUrl(finalPath));
}

效果如下图:


以上代码中 QString finalPath = "file:///" + folderPath;主要是为了处理路径中的 \\,如果 folderPath = C:/tmp/TargetFile 时,则可以不需要 "file:///",直接将 folderPath 作为 QUrl 的参数。