当前位置:   article > 正文

QT 打开指定目录并选中指定文件_qt在本地文件夹下选择文件

qt在本地文件夹下选择文件

目录
方法一、使用Qt自带的方法
方法二、使用windows自带工具

有时自动生成文件之后,点击某个按钮我们希望能够自动跳转到文件所在目录(打开之后不依附于运行程序),可能还需要选中该文件。
环境: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());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
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 ));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

方法二、使用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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/306753
推荐阅读
相关标签
  

闽ICP备14008679号