Qt Creator (source) has this functionality, it's trivial to copy it:
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);
}
}
Another, related blog post (with simpler code, I haven't tried it so I can't comment), is this.
Edit:
There is a bug in the original code when pathIn contains spaces on Windows. QProcess::startDetached will automatically quote a parameter if it contains spaces. However, Windows Explorer will not recognize a parameter wrapped in quotes, and will open the default location instead. Try it yourself in the Windows command line:
echo. > "C:a file with space.txt"
:: The following works
C:Windowsexplorer.exe /select,C:a file with space.txt
:: The following does not work
C:Windowsexplorer.exe "/select,C:a file with space.txt"
Thus,
QProcess::startDetached(explorer, QStringList(param));
is changed to
QString command = explorer + " " + param;
QProcess::startDetached(command);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…