經常我們的程序中需要訪問一些特殊的路徑,比如程序所在的路徑、用戶目錄路徑、臨時文件夾等。在 Qt 中實現這幾個功能所用的方法雖然都不難,但是各不相同,每次用到時還要現去查,很不方便。因此就寫了這篇博客,把這幾種需求的實現方式總結了一下。
比如我們有一個程序在:
C:/Qt/examples/tools/regexp/regexp.exe
1. 程序所在路徑
獲取 exe 程序所在路徑,QCoreApplication 類里就實現了相關的功能:
//輸出:C:/Qt/examples/tools/regexp
qDebug() << QCoreApplication::applicationDirPath();
2. 程序的完整名稱
可以這么寫:
//輸出:C:/Qt/examples/tools/regexp/regexp.exe
qDebug() << qApp->applicationFilePath();
3. 當前工作目錄
QDir 提供了一個靜態函數 currentPath() 可以獲取當前工作目錄,函數原型如下:
qDebug() << QDir::currentPath();
如果我們是雙擊一個程序運行的,那么程序的工作目錄就是程序所在目錄。
如果是在命令行下運行一個程序,那么運行程序時在命令行的哪個目錄,那個目錄就是當前目錄。
4. 用戶目錄路徑
Qt 4 中的方法。下面的方法只對 Qt 4 有效,Qt 5 已經刪除了 storageLocation() 方法。
QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
或者
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
這兩個方法的區別是 standardLocations() 返回值是 QStringList。當然對於 HomeLocation 來說這個 QStringList 中只有一個 QString。
還有另外一種方法,利用 QDir 類的一個靜態函數:
QDir::homePath();
博主的用戶目錄路徑為:"C:/Users/Administrator"。
5. 桌面路徑
Qt 4 中的方法。下面的方法只對 Qt 4 有效,Qt 5 已經刪除了 storageLocation() 方法。
QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
6. 程序數據存放路徑
通常我們會將程序所需的一些數據存入注冊表。但是有時需要存儲的數據太多,放在注冊表中就不適合了。這時我們就要找個專門的地方來放數據。以前我喜歡將數據直接放到程序所在目錄,但是后來發現我的程序運行時經常沒有權限對這個目錄下的文件進行寫操作。后來發現其實 Qt 早就替我們考慮過這些問題了。
Qt 4 中的方法。下面的方法只對 Qt 4 有效,Qt 5 已經刪除了 storageLocation() 方法。
QDesktopServices::storageLocation(QDesktopServices::DataLocation);
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
Qt 5.5 中引入了另一種方法:
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation);
這個方法一般來說和上面的方法得到的結果是相同的。按照 Qt 幫助文檔的解釋,這個方法可以確保返回的路徑非空。所以我認為應該優先選用這個方法。
7. 臨時文件路徑
Qt 4 中的方法。下面的方法只對 Qt 4 有效,Qt 5 已經刪除了 storageLocation() 方法。
QDesktopServices::storageLocation(QDesktopServices::TempLocation);
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QStandardPaths::standardLocations(QStandardPaths::TempLocation);
更傳統的方法是利用 QDir 的一個靜態函數 tempPath()。
QDir::tempPath();
在這個目錄下生成臨時文件和臨時目錄需要用到另外兩個類: QTemporaryFile 和 QTemporaryDir。就不展開介紹了,大家可以參考 qt 的幫助文檔。
至此,常用的各種特殊路徑就介紹的差不多了。剩下還有些不常用的,可以參考 QStandardPaths 類的介紹。
參考:
Qt 程序獲取程序所在路徑、用戶目錄路徑、臨時文件夾等特殊路徑的方法