赞
踩
目录
方法一、使用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());
}
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);
}
效果图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。