Qt程序关于路径、用户目录路径、临时文件夹位置获取方法
比如我們有一個(gè)程序在:
C:/Qt/examples/tools/regexp/regexp.exe
1. 程序所在目錄
QString QCoreApplication::applicationDirPath()
那么 qApp->applicationDirPath() 的結(jié)果是:
輸出:C:/Qt/examples/tools/regexp
2. 程序的完整名稱。那么可以這么寫:
qApp->applicationFilePath()輸出:
C:/Qt/examples/tools/regexp/regexp.exe
3. 當(dāng)前工作目錄
QDir 提供了一個(gè)靜態(tài)函數(shù) currentPath() 可以獲取當(dāng)前工作目錄
如果我們是雙擊一個(gè)程序運(yùn)行的,那么程序的工作目錄就是程序所在目錄。
如果是在命令行下運(yùn)行一個(gè)程序,那么運(yùn)行程序時(shí)在命令行的哪個(gè)目錄,那個(gè)目錄就是當(dāng)前目錄。
4. 用戶目錄路徑
Qt 5 中引入的方法
QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
這兩個(gè)方法的區(qū)別是 standardLocations() 返回值是 QStringList。當(dāng)然對(duì)于 HomeLocation 來說這個(gè) QStringList 中只有一個(gè) QString。
還有另外一種方法,利用 QDir 類的一個(gè)靜態(tài)函數(shù):
QDir::homePath();
5. 我的文檔路徑
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation);
6. 桌面路徑
QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QStandardPaths::standardLocations(QStandardPaths::DesktopLocation);
7. 程序數(shù)據(jù)存放路徑
通常我們會(huì)將程序所需的一些數(shù)據(jù)存入注冊表。但是有時(shí)需要存儲(chǔ)的數(shù)據(jù)太多,放在注冊表中就不適合了。這時(shí)我們就要找個(gè)專門的地方來放數(shù)據(jù)。以前我喜歡將數(shù)據(jù)直接放到程序所在目錄,但是后來發(fā)現(xiàn)我的程序運(yùn)行時(shí)經(jīng)常沒有權(quán)限對(duì)這個(gè)目錄下的文件進(jìn)行寫操作。后來發(fā)現(xiàn)其實(shí) Qt 早就替我們考慮過這些問題了。
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
Qt 5.5 中引入了另一種方法:
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation);
這個(gè)方法一般來說和上面的方法得到的結(jié)果是相同的。按照 Qt 幫助文檔的解釋,這個(gè)方法可以確保返回的路徑非空。所以我認(rèn)為應(yīng)該優(yōu)先選用這個(gè)方法。
8. 臨時(shí)文件路徑
Qt 5 中引入的方法。
QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QStandardPaths::standardLocations(QStandardPaths::TempLocation);
更傳統(tǒng)的方法是利用 QDir 的一個(gè)靜態(tài)函數(shù) tempPath()。
QDir::tempPath();
在這個(gè)目錄下生成臨時(shí)文件和臨時(shí)目錄需要用到另外兩個(gè)類: QTemporaryFile 和 QTemporaryDir。就不展開介紹了,大家可以參考 qt 的幫助文檔。
至此,常用的各種特殊路徑就介紹的差不多了。剩下還有些不常用的,可以參考 QStandardPaths 類的介紹。
endl;
總結(jié)
以上是生活随笔為你收集整理的Qt程序关于路径、用户目录路径、临时文件夹位置获取方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分布式中间件nacos入门解析
- 下一篇: 添加用户(过火绒)