1. 程式人生 > >QSetting 說明和簡單使用

QSetting 說明和簡單使用

文件 image pan 字符 provides 存儲格式 tgui 模板 ip地址

今天看到服務端代碼有一個QSetting。一開始以為是STL模板中的Set(弄到QT中改了個名字而已)。仔細一看嚇一跳,不是STL模板。是qt特有的一個類。

用來保存或讀取一些配置信息用的。看了後,感覺他太強大了,又很方便。不過有的地方當時沒看懂,查了好多資料才找到一點點有用的信息。特此記錄一下我難以平復的心情。

先看qt文檔:

技術分享

可以看到他的說明 和一些成員方法。再來看他的描述:

The QSettings class provides persistent platform-independent application settings.//類提供持久的獨立於平臺的應用程序設置。

Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions.//用戶通常期望應用程序記住其設置(窗口大小和位置,選項等)跨會話

This information is often stored in the system registry on Windows, and in property list files on OS X and iOS.//此信息通常存儲在Windows上的系統註冊表中,並在OS X和iOS的屬性列表文件中存儲

On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.//在UNIX系統中,在沒有標準的情況下,許多應用程序(包括KDE應用程序)使用INI文本文件。

QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner.//qsettings圍繞這些技術的抽象,使您可以保存和恢復在便攜式應用的設置方式。

It also supports custom storage formats.//它還支持自定義存儲格式

QSettings‘s API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort.//qsettings API是基於qvariant,讓你保存最值的基礎類型,如QString、qrect,和QImage,與最小的努力。

If all you need is a non-persistent memory-based structure, consider using QMap<QString, QVariant> instead.//如果你需要的是一個基於結構的非持續性的記憶,可以考慮使用QMAP < QString,qvariant >代替

就不翻譯了。

QSetting有三種模式:

  1. QSettings::NativeFormat.將設置從平臺上存儲到本地磁盤上。在windows平臺上,存儲到註冊表中,帶OSX or iOS存儲到本地文件。在LINUX中保存到.INI格式的配置文件中
  2. QSettings::IniFormat.保存到.INI格式的配置文件
  3. QSettings::InvalidFormat.存儲到註冊表中

你的*.config文件中有這麽一行數據:dbIp=192.168.31.124

為了讀取IP地址,就可以碼如下代碼:

QSetting conf("path/my.config");
QString str = conf.value("dbIp","192.168.31.124");

聲明一個QSetting類對象,將配置文件的路徑添加進去。然後使用類的成員方法value即可獲取對應KEY的值。第二個字符串表示,如果配置文件中不存在此key,則直接將第二個參數復制給str.

如果有多個字段值在配置文件中的話,就需要將分段的名字也寫到key中去

[Server]
dbIp=19.168.1.127
dbPort=40001
[DB]
IP=123
PORT=159

想要讀取dbIp需要更改key如下:

QSring str=conf.value("Server/dbIp","19.168.1.127");

QSetting 說明和簡單使用