QSetting 说明和简单使用

今天看到服务端代码有一个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");
作者:first_semon
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有问题,欢迎交流
原文地址:https://www.cnblogs.com/first-semon/p/6951746.html