1. 程式人生 > >Qt程序關於路徑、用戶目錄路徑、臨時文件夾位置獲取方法

Qt程序關於路徑、用戶目錄路徑、臨時文件夾位置獲取方法

lis 靜態函數 目錄下的文件 兩個 top 存儲 class ber ron

  比如我們有一個程序在:

  C:/Qt/examples/tools/regexp/regexp.exe

1. 程序所在目錄

  QString QCoreApplication::applicationDirPath()

  那麽 qApp->applicationDirPath() 的結果是:

  輸出:C:/Qt/examples/tools/regexp  

2. 程序的完整名稱。那麽可以這麽寫:

  qApp->applicationFilePath()

  輸出:C:/Qt/examples/tools/regexp/regexp.exe

3. 當前工作目錄

 QDir 提供了一個靜態函數 currentPath() 可以獲取當前工作目錄

  如果我們是雙擊一個程序運行的,那麽程序的工作目錄就是程序所在目錄。

  如果是在命令行下運行一個程序,那麽運行程序時在命令行的哪個目錄,那個目錄就是當前目錄。

4. 用戶目錄路徑

  Qt 5 中引入的方法

  QStandardPaths::writableLocation(QStandardPaths::HomeLocation);

  QStandardPaths::standardLocations(QStandardPaths::HomeLocation);

  這兩個方法的區別是 standardLocations() 返回值是 QStringList。當然對於 HomeLocation 來說這個 QStringList 中只有一個 QString。

  還有另外一種方法,利用 QDir 類的一個靜態函數:

  QDir::homePath();

5. 我的文檔路徑

   Qt 5 中引入的方法。

  QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);

  QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);

6. 桌面路徑

  QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);

  QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);

7. 程序數據存放路徑

  通常我們會將程序所需的一些數據存入註冊表。但是有時需要存儲的數據太多,放在註冊表中就不適合了。這時我們就要找個專門的地方來放數據。以前我喜歡將數據直接放到程序所在目錄,但是後來發現我的程序運行時經常沒有權限對這個目錄下的文件進行寫操作。後來發現其實 Qt 早就替我們考慮過這些問題了。

  Qt 5 中引入的方法。

  QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);

  QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);

  Qt 5.5 中引入了另一種方法:  

  QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);

  QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation);

  這個方法一般來說和上面的方法得到的結果是相同的。按照 Qt 幫助文檔的解釋,這個方法可以確保返回的路徑非空。所以我認為應該優先選用這個方法。

8. 臨時文件路徑

  Qt 5 中引入的方法。

  QStandardPaths::writableLocation(QStandardPaths::TempLocation);

QStandardPaths::standardLocations(QStandardPaths::TempLocation);

  更傳統的方法是利用 QDir 的一個靜態函數 tempPath()。

  QDir::tempPath();

  在這個目錄下生成臨時文件和臨時目錄需要用到另外兩個類: QTemporaryFile 和 QTemporaryDir。就不展開介紹了,大家可以參考 qt 的幫助文檔。

至此,常用的各種特殊路徑就介紹的差不多了。剩下還有些不常用的,可以參考 QStandardPaths 類的介紹。

endl;

Qt程序關於路徑、用戶目錄路徑、臨時文件夾位置獲取方法