Qt创建者 http://download.qt.io/official_releases/qtcreator/ (source https://github.com/qt-creator/qt-creator/blob/master/src/plugins/coreplugin/fileutils.cpp#L67) 有这个功能,复制它很简单:
void FileUtils::showInGraphicalShell(QWidget *parent, const QString &pathIn)
{
const QFileInfo fileInfo(pathIn);
// Mac, Windows support folder or file.
if (HostOsInfo::isWindowsHost()) {
const FileName explorer = Environment::systemEnvironment().searchInPath(QLatin1String("explorer.exe"));
if (explorer.isEmpty()) {
QMessageBox::warning(parent,
QApplication::translate("Core::Internal",
"Launching Windows Explorer Failed"),
QApplication::translate("Core::Internal",
"Could not find explorer.exe in path to launch Windows Explorer."));
return;
}
QStringList param;
if (!fileInfo.isDir())
param += QLatin1String("/select,");
param += QDir::toNativeSeparators(fileInfo.canonicalFilePath());
QProcess::startDetached(explorer.toString(), param);
} else if (HostOsInfo::isMacHost()) {
QStringList scriptArgs;
scriptArgs << QLatin1String("-e")
<< QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
.arg(fileInfo.canonicalFilePath());
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
scriptArgs.clear();
scriptArgs << QLatin1String("-e")
<< QLatin1String("tell application \"Finder\" to activate");
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
} else {
// we cannot select a file here, because no file browser really supports it...
const QString folder = fileInfo.isDir() ? fileInfo.absoluteFilePath() : fileInfo.filePath();
const QString app = UnixUtils::fileBrowser(ICore::settings());
QProcess browserProc;
const QString browserArgs = UnixUtils::substituteFileBrowserParameters(app, folder);
bool success = browserProc.startDetached(browserArgs);
const QString error = QString::fromLocal8Bit(browserProc.readAllStandardError());
success = success && error.isEmpty();
if (!success)
showGraphicalShellError(parent, app, error);
}
}
另一篇相关的博客文章(代码更简单,我还没有尝试过,所以我无法发表评论)是this http://lynxline.com/show-in-finder-show-in-explorer/.
Edit:
在 Windows 上,当 pathIn 包含空格时,原始代码中存在错误。QProcess::startDetached http://doc.qt.io/qt-5/qprocess.html#startDetached如果参数包含空格,将自动引用该参数。但是,Windows 资源管理器无法识别用引号引起来的参数,而是会打开默认位置。在 Windows 命令行中亲自尝试一下:
echo. > "C:\a file with space.txt"
:: The following works
C:\Windows\explorer.exe /select,C:\a file with space.txt
:: The following does not work
C:\Windows\explorer.exe "/select,C:\a file with space.txt"
Thus,
QProcess::startDetached(explorer, QStringList(param));
更改为
QString command = explorer + " " + param;
QProcess::startDetached(command);