Qt Creator có chức năng này, nó tầm thường để sao chép nó:
void FolderNavigationWidget::showInGraphicalShell(QWidget *parent, const QString &pathIn)
{
// Mac, Windows support folder or file.
#if defined(Q_OS_WIN)
const QString explorer = Environment::systemEnvironment().searchInPath(QLatin1String("explorer.exe"));
if (explorer.isEmpty()) {
QMessageBox::warning(parent,
tr("Launching Windows Explorer failed"),
tr("Could not find explorer.exe in path to launch Windows Explorer."));
return;
}
QString param;
if (!QFileInfo(pathIn).isDir())
param = QLatin1String("/select,");
param += QDir::toNativeSeparators(pathIn);
QString command = explorer + " " + param;
QProcess::startDetached(command);
#elif defined(Q_OS_MAC)
Q_UNUSED(parent)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e")
<< QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
.arg(pathIn);
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
scriptArgs.clear();
scriptArgs << QLatin1String("-e")
<< QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);
#else
// we cannot select a file here, because no file browser really supports it...
const QFileInfo fileInfo(pathIn);
const QString folder = fileInfo.absoluteFilePath();
const QString app = Utils::UnixUtils::fileBrowser(Core::ICore::instance()->settings());
QProcess browserProc;
const QString browserArgs = Utils::UnixUtils::substituteFileBrowserParameters(app, folder);
if (debug)
qDebug() << browserArgs;
bool success = browserProc.startDetached(browserArgs);
const QString error = QString::fromLocal8Bit(browserProc.readAllStandardError());
success = success && error.isEmpty();
if (!success)
showGraphicalShellError(parent, app, error);
#endif
}
khác, liên quan đến bài viết trên blog (với mã đơn giản, tôi đã không thử nó vì vậy tôi có thể 't bình luận), là this.
Chỉnh sửa:
Có lỗi trong mã gốc khi pathIn chứa khoảng trắng trên Windows. QProcess::startDetached sẽ tự động trích dẫn một tham số nếu nó chứa dấu cách. Tuy nhiên, Windows Explorer sẽ không nhận ra một tham số được bao bọc trong dấu ngoặc kép và sẽ mở vị trí mặc định thay thế. Thử nó cho mình trong dòng lệnh 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"
Như vậy,
QProcess::startDetached(explorer, QStringList(param));
được thay đổi để
QString command = explorer + " " + param;
QProcess::startDetached(command);
Để làm rõ: ý của bạn là khi bạn nhấp vào "Hiển thị trong Trình đơn tìm kiếm "hoặc" Hiển thị trong Explorer "? –
@Austin Vâng, ý tôi là chính xác một cái gì đó như "Tiết lộ trong Finder" hoặc "Hiển thị trong Explorer" – nnc