QStandardPaths 獲得系統特定目錄

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();
}
執行結果如下:







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章