Qt打开指定目录并选中指定文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a844651990/article/details/82789746


  有时自动生成文件之后,点击某个按钮我们希望能够自动跳转到文件所在目录(打开之后不依附于运行程序),可能还需要选中该文件。
环境:win10 + Qt5.9.6 MinGW

方法一、使用Qt自带的方法

  使用QDesktopServices::openUrl(const QUrl &url)静态函数,可以跳到指定的目录,但是目前还没找到选中文件的方法。

void MainWindow::on_createFileBtn_clicked()
{
    QFile file;
    file.setFileName(QApplication::applicationDirPath() + "/" +
                     QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") +
                     ".txt");
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Create file failed!";
        return;
    }
    ui->filePathLE->setText(file.fileName());
}

void MainWindow::on_openFolderBtn_clicked()
{
    if (ui->filePathLE->text().isEmpty())
        return;

    QString str = ui->filePathLE->text();
    str.remove(str.split("/").last());
    QDesktopServices::openUrl(QUrl(str ));
}

效果图:
在这里插入图片描述

方法二、使用windows自带工具

  QProcess配合explorer可以自动跳转到指定目录并且选中该文件。** 需要注意的是,只能识别 路径只能识别 ''符号,因此需要替换一下**

void MainWindow::on_openFolderBtn_clicked()
{
    if (ui->filePathLE->text().isEmpty())
        return;

    QProcess process;
    QString filePath = ui->filePathLE->text();
    filePath.replace("/", "\\"); // 只能识别 "\"
    QString cmd = QString("explorer.exe /select,\"%1\"").arg(filePath);
    qDebug() << cmd;
    process.startDetached(cmd);
}

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/a844651990/article/details/82789746
今日推荐