Подтвердить что ты не робот

Как "показать в Finder" или "Show in Explorer" с Qt

Можно ли открыть папку в Проводнике Windows/Finder OS X, а затем выбрать/выделить один файл в этой папке и сделать это на кросс-платформенном пути? Прямо сейчас, я делаю что-то вроде

QDesktopServices::openUrl( QUrl::fromLocalFile( path ) );

где path - полный путь к папке, которую я хочу открыть. Очевидно, это просто откроет папку, и мне придется отследить файл, который мне нужен вручную. Это небольшая проблема, когда в этой папке есть тысячи файлов.

Если я создаю путь к определенному файлу в этой папке, тогда этот файл открыт с приложением по умолчанию для этого типа mime, и это не то, что мне нужно. Вместо этого мне нужна функциональность, эквивалентная "Reveal in Finder" или "Show in Explorer".

4b9b3361

Ответ 1

У Qt Creator (source) есть эта функция, тривиальная копия:

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);
    }
}

Другое, связанное сообщение в блоге (с более простым кодом, я не пробовал, поэтому не могу комментировать), вот что.

Редактировать:

В исходном коде есть ошибка, когда pathIn содержит пробелы в Windows. QProcess :: startDetached автоматически укажет параметр, если он содержит пробелы. Однако Windows Explorer не распознает параметр, заключенный в кавычки, и вместо этого откроет место по умолчанию. Попробуйте сами в командной строке 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"

Таким образом,

QProcess::startDetached(explorer, QStringList(param));

изменен на

QString command = explorer + " " + param;
QProcess::startDetached(command);

Ответ 2

Вероятно, вы можете использовать QFileDialog::getOpenFileName чтобы получить имя файла. Документация доступна здесь. Вышеуказанная функция вернет полный путь, включая имя файла и его расширение, если оно есть..

Тогда вы можете дать

QDesktopServices::openUrl(path);

чтобы открыть файл по умолчанию, где path будет QString возвращаемый QFileDialog::getOpenFileName.

Надеюсь, поможет..

Ответ 3

Открыть файл в проводнике Windows (не в браузере)

void OpenFileInExplorer()
{
   QString path = "C:/exampleDir/example.txt";

   QStringList args;

   args << "/select," << QDir::toNativeSeparators(path);

   QProcess *process = new QProcess(this);
   process->start("explorer.exe", args); 

}

Ответ 4

Вот код, с которым я пошёл, основываясь на результатах предыдущего ответа. Эта версия не зависит от других методов в Qt Creator, принимает файл или каталог и имеет режим возврата для обработки ошибок и других платформ:

void Util::showInFolder(const QString& path)
{
    QFileInfo info(path);
#if defined(Q_OS_WIN)
    QStringList args;
    if (!info.isDir())
        args << "/select,";
    args << QDir::toNativeSeparators(path);
    if (QProcess::startDetached("explorer", args))
        return;
#elif defined(Q_OS_MAC)
    QStringList args;
    args << "-e";
    args << "tell application \"Finder\"";
    args << "-e";
    args << "activate";
    args << "-e";
    args << "select POSIX file \"" + path + "\"";
    args << "-e";
    args << "end tell";
    args << "-e";
    args << "return";
    if (!QProcess::execute("/usr/bin/osascript", args))
        return;
#endif
    QDesktopServices::openUrl(QUrl::fromLocalFile(info.isDir()? path : info.path()));
}

Ответ 5

Это решение работает как на Windows, так и на Mac:

void showFileInFolder(const QString &path){
    #ifdef _WIN32    //Code for Windows
        QProcess::startDetached("explorer.exe", {"/select,", QDir::toNativeSeparators(path)});
    #elif defined(__APPLE__)    //Code for Mac
        QProcess::execute("/usr/bin/osascript", {"-e", "tell application \"Finder\" to reveal POSIX file \"" + path + "\""});
        QProcess::execute("/usr/bin/osascript", {"-e", "tell application \"Finder\" to activate"});
    #endif
}