1、获取程序所在目录:QString QCoreApplication::applicationDirPath()
2、获取程序完成目录及名称:QString QCoreApplication::applicationFilePath()
3、获取当前工作目录:QString QDir::currentPath()
4、获取家目录:QString QDir::homePath()
5、获取根目录:QString QDir::rootPath()
6、获取临时文件目录:QString QDir::tempPath()
7、用户目录路径
Qt 5 中引入的方法
QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
这两个方法的区别是 standardLocations() 返回值是 QStringList。当然对于 HomeLocation 来说这个 QStringList 中只有一个 QString。
还有另外一种方法,利用 QDir 类的一个静态函数:
QDir::homePath();
8、我的文档路径
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
9、桌面路径
QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
10、程序数据存放路径
通常我们会将程序所需的一些数据存入注册表。但是有时需要存储的数据太多,放在注册表中就不适合了。这时我们就要找个专门的地方来放数据。以前我喜欢将数据直接放到程序所在目录,但是后来发现我的程序运行时经常没有权限对这个目录下的文件进行写操作。后来发现其实 Qt 早就替我们考虑过这些问题了。
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
Qt 5.5 中引入了另一种方法:
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation);
这个方法一般来说和上面的方法得到的结果是相同的。按照 Qt 帮助文档的解释,这个方法可以确保返回的路径非空。所以我认为应该优先选用这个方法。
11、临时文件路径
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QStandardPaths::standardLocations(QStandardPaths::TempLocation);
更传统的方法是利用 QDir 的一个静态函数 tempPath()。
QDir::tempPath();
在这个目录下生成临时文件和临时目录需要用到另外两个类: QTemporaryFile 和 QTemporaryDir。就不展开介绍了,大家可以参考 qt 的帮助文档。
至此,常用的各种特殊路径就介绍的差不多了。剩下还有些不常用的,可以参考 QStandardPaths 类的介绍。