QStandardPaths提供了一系列的静态方法,供我们用来获得当前系统配置下的特定的目录。比如,已Windows系统为例,有用户目录,图片目录,视频目录,桌面等等。该类的使用也非常方便,因为它只有几个静态方法,我们可以直接调用。
QString QStandardPaths::displayName(StandardLocation type)根据传入的位置类型,返回一个该位置名称的的字符串。其中,StandardLocation是该类的枚举类型,代表了操作系统中的特定目录。QString QStandardPaths::findExecutable(const QString &executableName, const QStringList &paths = QStringList())在特定目录下搜索某个可执行程序,若不传如目录,则表示在系统目录中搜索,在大部分系统中,即为PATH所表示的目录位置。所以,如果既想搜索系统目录又想搜索自己指定的目录,则需要调用该函数两次,一次传入目录参数,一次不传该参数即可。
并且,在Windows平台上,不需要为executableName添加.exe后缀,该函数会自动为我们追加。
该函数会返回可执行文件的绝对路径;如果没找到,则返回空字符串。
QString QStandardPaths::locate(StandardLocation type, const QString &fileName, LocateOptions options = LocateFile)
QStringList QStandardPaths::locateAll(StandardLocation type, const QString &fileName, LocateOptions options = LocateFile)在标准目录下查询一个或多个指定名字的文件或目录。
QStringList QStandardPaths::standardLocations(StandardLocation type)返回属于类型type的所有目录。返回的目录列表按优先级从高到低排序。如果存在writableLocation(),则该目录优先。
下面,我们通过一个例子,以Windows系统为例,打印几个我们平时开发中常用的目录位置:
新建一个Qt控制台程序即可:
#include <QCoreApplication>
#include <QStandardPaths>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "DesktopLocation: " << QStandardPaths::displayName(QStandardPaths::DesktopLocation);
qDebug() << "DocumentsLocation: " << QStandardPaths::displayName(QStandardPaths::DocumentsLocation);
qDebug() << "ApplicationsLocation: " << QStandardPaths::displayName(QStandardPaths::ApplicationsLocation);
qDebug() << "MusicLocation: " << QStandardPaths::displayName(QStandardPaths::MusicLocation);
qDebug() << "MoviesLocation: " << QStandardPaths::displayName(QStandardPaths::MoviesLocation);
qDebug() << "PicturesLocation: " << QStandardPaths::displayName(QStandardPaths::PicturesLocation);
qDebug() << "TempLocation: " << QStandardPaths::displayName(QStandardPaths::TempLocation);
qDebug() << "HomeLocation: " << QStandardPaths::displayName(QStandardPaths::HomeLocation);
qDebug() << "DataLocation: " << QStandardPaths::displayName(QStandardPaths::DataLocation);
qDebug() << "CacheLocation: " << QStandardPaths::displayName(QStandardPaths::CacheLocation);
qDebug() << "DownloadLocation: " << QStandardPaths::displayName(QStandardPaths::DownloadLocation);
return a.exec();
}
执行结果如下:
QStandardPaths类提供了一种便捷的方式,用于在不同操作系统下获取特定的系统目录,如用户目录、图片和视频目录等。在Windows上,无需手动添加.exe后缀来获取可执行文件路径。本文通过一个简单的Qt控制台程序示例,演示了如何在Windows系统中获取常见的开发目录。

2万+

被折叠的 条评论
为什么被折叠?



