在Windows操作系統中,大多把配置文件信息寫在注冊表當中,或寫在*.ini文件中,對於這兩種操作都有相應的Windows API函數,在以前的文章中都提及過,這里就不多說了~
在Qt中,提供了一個相應的配置文件的類QSetting,使用QSetting類,可以將用戶設置以及應用程序的設置輕松存儲在磁盤中。
QSettings::Format(配置存儲格式)分為NativeFormat、IniFormat、InvalidFormat。這里主要講的是NativeFormat和IniFormat。
QSettings::NativeFormat:在Windows中,利用系統注冊表來存儲;在 Mac OS X中,使用系統的CFPreferences機制來存儲(使用Core Foundation Preference API);在其他平台中,設置則存儲在文本文件中。
QSettings::IniFormat:讀寫*.ini格式的配置文件,NativeFormat在某些操作系統中的擴展名是*.conf。
QSettings::Scope(配置存儲范圍)分為UserScope、SystemScope。
QSettings::UserScope:用戶環境,設置在當前用戶的特定位置中。
QSettings::SystemScope:系統環境,設置在全局型,所有用戶均可獲得。
以下是對應QSettings::Format和QSettings::Scope存放的默認路徑位置,其中*表示的是對應的程序名稱:
Platform Format Scope Path
Windows NativeFormat UserScope HKEY_CURRENT_USER\Software\*
SystemScope HKEY_LOCAL_MACHINE\Software\*
IniFormat UserScope %APPDATA%\*.ini
SystemScope %COMMON_APPDATA%\*.ini
Unix NativeFormat UserScope $HOME/.config/*.conf
SystemScope /etc/xdg/*.conf
IniFormat UserScope $HOME/.config/*.ini
SystemScope /etc/xdg/*.ini
Mac OS X NativeFormat UserScope $HOME/Library/Preferences/com.*.plist
SystemScope /Library/Preferences/com.*.plist
IniFormat UserScope $HOME/.config/*.ini
SystemScope /etc/xdg/*.ini
在讀寫時,路徑名必須是"/"而不是"\\"等。否則不能讀寫,注意。
以Windows XP平台為例,舉倆個例子程序~
■、讀寫注冊表
//Format為QSettings::NativeFormat
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office",
QSettings::NativeFormat);
//設置鍵值信息
settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0);
//獲取鍵值信息
int value = settings.value("11.0/Outlook/Security/DontTrustInstalledFiles").toInt();
對應的值可是bool,double,QString,QStringList,或者是其他QVariant支持的數據類型,也包括注冊過的用戶自定義類型。
刪除設置對應的是settings->remove( const QString & key );
■、讀取ini配置文件
先定義下software.ini文件的格式,比較簡單:
[bolg]
Name = "vic.MINg"
//Format為QSettings::IniFormat
QSettings *setIni=new QSettings ("software", QSettings::IniFormat);
//設置鍵值信息
setIni->beginGroup("bolg");
setIni->setValue("Name", "vic.MINg");
setIni->endGroup();
//獲取鍵值信息
setIni->beginGroup("bolg");
QString resault = setIni->value("Name").toString();
setIni->endGroup();
qDebug()<<resault;
QSetting的應用並不難,但很有用,一些更細致的操作用法,可以參看幫助文檔!
可以參照示例:$QTDIR\examples\tools\settingseditor
http://cool.worm.blog.163.com/blog/static/643390062008426102655150/