QString filePath = QFileDialog::getOpenFileName(this, tr("选择文件"), global_img_dir, tr("*"));
QString filePath = QFileDialog::getOpenFileName( nullptr, "选择文件",
QCoreApplication::applicationDirPath(), "文本文件(*.txt);;所有文件(*.*)");
QString folderPath = QFileDialog::getExistingDirectory( this, "选择文件夹", QDir::homePath() );
上面例子中的路径参数:
1.global_img_dir—— 这是一个你自己定义的变量,通常有以下几种设置方式:
方式1:硬编码路径(不推荐) QString global_img_dir = "C:/Users/YourName/Pictures";
方式2:使用相对路径 QString global_img_dir = "./images"; // 程序运行目录下的 images 文件夹
方式3:使用标准路径(推荐)
QString global_img_dir = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
// 其他常用标准路径:
// QStandardPaths::DocumentsLocation - 文档目录
// QStandardPaths::DesktopLocation - 桌面目录
// QStandardPaths::DownloadLocation - 下载目录
// QStandardPaths::HomeLocation - 家目录
方式4:记住上次打开的路径(最实用)
// 在头文件中声明静态变量
static QString lastUsedPath = QDir::homePath();
// 打开对话框时使用上次路径
QString filePath = QFileDialog::getOpenFileName(this, "选择文件", lastUsedPath);
if (!filePath.isEmpty())
{
lastUsedPath = QFileInfo(filePath).absolutePath(); // 记住路径
// 处理文件...
}
2. QDir::homePath()—— 用户家目录 ,系统自动获取,Windows系统下是: C:\Users\用户名
3. QCoreApplication::applicationDirPath()—— 程序所在目录,获取当前可执行文件所在的目录,例如: 如果你的程序在 D:/MyApp/release/myapp.exe • 则返回 D:/MyApp/release