QSettings 类
QSettings 类为应用程序提供独立于平台的持久化设置. 更多...
头文件: | #include <QSettings> |
qmake: | QT += core |
基类: | QObject |
注: 这个类的所有函数都是 可重入的.
注: 这个类的所有函数都是 线程安全的:
- registerFormat(const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity)
公有类型
enum | Format { NativeFormat, Registry32Format, Registry64Format, IniFormat, InvalidFormat } |
typedef | ReadFunc |
enum | Scope { UserScope, SystemScope } |
typedef | SettingsMap |
enum | Status { NoError, AccessError, FormatError } |
typedef | WriteFunc |
公有函数
QSettings(const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR) | |
QSettings(Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR) | |
QSettings(Format format, Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR) | |
QSettings(const QString &fileName, Format format, QObject *parent = Q_NULLPTR) | |
QSettings(QObject *parent = Q_NULLPTR) | |
~QSettings() | |
QStringList | allKeys() const |
QString | applicationName() const |
void | beginGroup(const QString &prefix) |
int | beginReadArray(const QString &prefix) |
void | beginWriteArray(const QString &prefix, int size = -1) |
QStringList | childGroups() const |
QStringList | childKeys() const |
void | clear() |
bool | contains(const QString &key) const |
void | endArray() |
void | endGroup() |
bool | fallbacksEnabled() const |
QString | fileName() const |
Format | format() const |
QString | group() const |
QTextCodec * | iniCodec() const |
bool | isWritable() const |
QString | organizationName() const |
void | remove(const QString &key) |
Scope | scope() const |
void | setArrayIndex(int i) |
void | setFallbacksEnabled(bool b) |
void | setIniCodec(QTextCodec *codec) |
void | setIniCodec(const char *codecName) |
void | setValue(const QString &key, const QVariant &value) |
Status | status() const |
void | sync() |
QVariant | value(const QString &key, const QVariant &defaultValue = QVariant()) const |
- 32个公有函数继承自 QObject
静态公有成员
Format | defaultFormat() |
Format | registerFormat(const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive) |
void | setDefaultFormat(Format format) |
void | setPath(Format format, Scope scope, const QString &path) |
- 11个继承自QObject的静态公有成员
重新实现的受保护的函数
virtual bool | event(QEvent *event) |
- 9个继承自 QObject的受保护的函数
其他继承成员
详细描述
QSettings 类为应用程序提供独立于平台的持久化配置.
在跨多个会话时, 用户通常期望应用程序能记忆它的配置(如窗口大小, 位置, 选项等). 在Windows系统上, 这些信息通常存储在系统注册表中, 在 macOS 和 iOS 操作系统上, 这些信息通常存储在属性列表文件中. 在Unix系统, 由于缺乏标准, 许多应用程序(包括KDE程序)使用INI文件存储.
QSettings是围绕这些技术的一个抽象实现, 使你以一种可移植的方式保存和恢复应用程序的配置. 它还支持 自定义存储格式.
QSettings 的API是基于 QVariant, 允许你以最少的工作量保存大部分数据类型, 例如 QString, QRect, and QImage.
如果你只需要一个非持久的内存结构, 那么考虑使用 QMap<QString, QVariant> 替代.
基本用法
当创建一个 QSettings 对象, 你必须传入你的公司或组织的名称, 还有应用程序的名称. 例如, 如果你的产品叫Star Runner, 你的公司叫MySoft, 那么你应该以下面的方式创建 QSettings 对象:
QSettings settings("MySoft", "Star Runner");
QSettings 对象既可以创建在栈上, 也可以创建在堆上 (如. 使用 new
). 创建和销毁一个 QSettings 对象是非常快的.
如果你在应用程序的很多地方使用 QSettings , 你可以使用 QCoreApplication::setOrganizationName() 和 QCoreApplication::setApplicationName()设置默认的公司名称和应用程序名称, 然后调用 QSettings 的默认构造函数:
QCoreApplication::setOrganizationName("MySoft"); QCoreApplication::setOrganizationDomain("mysoft.com"); QCoreApplication::setApplicationName("Star Runner"); ... QSettings settings;
(这里, 我们设置了组织的网络域名. 自从macOS 和 iOS 系统采用网络域名区分应用程序后, 如果应用程序没有设置网络域名, 系统会利用组织名称生成一个假域名. 详见 Platform-Specific Notes .)
QSettings 存储应用程序设置. 每一个设置包含两部分, QString 表示设置名称 (the key) , QVariant 存储与之关联的数据. 使用 setValue()保存一个设置. 例如:
settings.setValue("editor/wrapMargin", 68);
如果应用程序设置时, 存在相同的key, 新的值将替换已有的值. 为了提高效率, 并不是每一次修改都会立即持久化存储. (你总是可以调用 sync() 提交你的修改.)
你能使用 value()获取设置的值:
int margin = settings.value("editor/wrapMargin").toInt();
如果没有相应的设置, QSettings 会返回一个空的 QVariant (空的QVariant转为整型是0). 你调用 value()的时候, 可以在第二个参数传入默认值:
int margin = settings.value("editor/wrapMargin", 80).toInt();
调用 contains() 检测给定的key值是否存在. 调用 remove() 移除已有的设置. 调用 allKeys() 获取包含所有key的列表. 调用 clear()清空所有设置.
QVariant and GUI 数据类型
由于 QVariant 是Qt Core 模块的一部分, 它不能提供直接转换Qt GUI模块的数据类型的函数, 例如 QColor, QImage, and QPixmap. 换句话说, 在QVariant中没有这些函数 toColor()
, toImage()
, 或 toPixmap()
.
你可以使用 QVariant::value() 或者 qVariantValue() 模板函数实现Qt GUI模块的数据转换. 例如:
QSettings settings("MySoft", "Star Runner"); QColor color = settings.value("DataPump/bgcolor").value<QColor>();
逆向转换 (例如., 从 QColor 到 QVariant) 可以被 QVariant 自动处理, 包括GUI 模块相关的数据类型:
QSettings settings("MySoft", "Star Runner"); QColor color = palette().background().color(); settings.setValue("DataPump/bgcolor", color);
使用 qRegisterMetaType() 和 qRegisterMetaTypeStreamOperators() 注册的自定义数据类型也能用 QSettings 存储.
Section and Key 语法
QSettings的key值可以包含Unicode字符. windows的注册表和INI文件区分大小写, macOS 和 iOS 的CFPreferences API也区分大小写. 为了避免一些兼容性问题, 请遵守下面规则:
- 总是使用大小写一致的key值. 例如, 如果你在应用程序中使用 "text fonts" 作为key值, 那么在其他地方, 不要使用 "Text Fonts" .
- 避免使用相同的key值(不区分大小写). 例如, 如果你已经使用key值 "MainWindow", 不要使用另一个key值 "mainwindow".
- 不要在section和key使用斜杠 ('/' 和 '\'); 反斜杠是用来划分层级 (如下). 在windows中, QSettings 会用'/'替换'\', 无法区分'\'和'/'.
你可以使用'/'作为key值的层级区分, 类似于Unix的文件路径. 例如:
settings.setValue("mainwindow/size", win->size()); settings.setValue("mainwindow/fullScreen", win->isFullScreen()); settings.setValue("outputpanel/visible", panel->isVisible());
如果你想存取许多相同前缀的设置, 你可以使用 beginGroup() 和 endGroup() 明确指明. 下面给出与上面一样效果的示例, 这次使用分组机制:
settings.beginGroup("mainwindow"); settings.setValue("size", win->size()); settings.setValue("fullScreen", win->isFullScreen()); settings.endGroup(); settings.beginGroup("outputpanel"); settings.setValue("visible", panel->isVisible()); settings.endGroup();
如果使用beginGroup()设置一个分组, 大部分函数的行为都会发生改变, 分组能递归调用.
除了分组外, QSettings 也支持 "array" 概念. 详见 beginReadArray() 和 beginWriteArray().
备选机制
假设你使用组织名(MySoft)和应用程序名称(Star Runner)创建一个 QSettings 对象. 当你搜索一个值时, Qt会按照一定的顺序从4个位置搜索:
- a user-specific location for the Star Runner application
- a user-specific location for all applications by MySoft
- a system-wide location for the Star Runner application
- a system-wide location for all applications by MySoft
(Qt如何在不同平台存放这些信息详见 Platform-Specific Notes .)
如果在第一个位置不能查找到key值, 继续在第二个位置查找, 以此类推. 这种方式可以让你将每个用户都需要用到的配置数据存储在系统位置. 调用 setFallbacksEnabled(false)可以关闭这种机制.
虽然, 配置信息可以存储在4个不同的位置, 但是, Qt只会使用第一个位置 (the user-specific location for the application at hand). 如果想存储在其他位置, 请省略应用程序名称或作用域 QSettings::SystemScope (不同于 QSettings::UserScope, 缺省默认值).
查看如下示例:
QSettings obj1("MySoft", "Star Runner"); QSettings obj2("MySoft"); QSettings obj3(QSettings::SystemScope, "MySoft", "Star Runner"); QSettings obj4(QSettings::SystemScope, "MySoft");
下表总结在不同的条件, QSettings 对象存储位置. "X" 表示这个位置 QSettings 对象的主要存取位置; "o" 表示这个位置是取配置数据时备选查找位置.
Locations | obj1 | obj2 | obj3 | obj4 |
---|---|---|---|---|
1. User, Application | X | |||
2. User, Organization | o | X | ||
3. System, Application | o | X | ||
4. System, Organization | o | o | o | X |
这个机制的优势是你不需要设置任何文件名或注册路径, 就可以在不同的平台实现配置存取.
如果你想使用INI文件替换本地API, 你可以使用 QSettings::IniFormat 作为 QSettings 构造函数的第一个参数, 其他参数分别是作用域, 组织名和应用程序名称:
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "MySoft", "Star Runner");
Settings Editor 范例为你展示在备选机制开关条件下, 配置数据在不同的位置存取.
恢复GUI应用程序的状态
QSettings 经常用于存放GUI应用程序的状态数据. 下面的示例说明如何使用 QSettings 存取应用程序主窗口的位置和大小.
void MainWindow::writeSettings() { QSettings settings("Moose Soft", "Clipper"); settings.beginGroup("MainWindow"); settings.setValue("size", size()); settings.setValue("pos", pos()); settings.endGroup(); } void MainWindow::readSettings() { QSettings settings("Moose Soft", "Clipper"); settings.beginGroup("MainWindow"); resize(settings.value("size", QSize(400, 400)).toSize()); move(settings.value("pos", QPoint(200, 200)).toPoint()); settings.endGroup(); }
Window Geometry 解释在设置窗口位置和大小时, 为什么调用 QWidget::resize() 和 QWidget::move() 比调用 QWidget::setGeometry() 更好.
如下所示, readSettings()
和 writeSettings()
函数必须分别在主窗体的构造函数和关闭事件处理函数中调用:
MainWindow::MainWindow() { ... readSettings(); } void MainWindow::closeEvent(QCloseEvent *event) { if (userReallyWantsToQuit()) { writeSettings(); event->accept(); } else { event->ignore(); } }
查看 Application 示例, 对于一个功能齐全的应用程序, 如何使用 QSettings.
在多线程或多进程中访问设置
QSettings 是 reentrant. 这意味着你可以在不同的线程中直接使用不同的 QSettings 对象. 即使 QSettings 对象使用磁盘上相同的文件 (或注册表中相同的条目), 这个保证仍然有效. 如果一条设置被一个 QSettings 对象修改, 这条修改会立即被进程中操作相同位置的其他 QSettings 对象看到.
在多进程中, 使用QSettings 对象在相同的位置存取设置也是安全的. 你可以使用文件锁和智能合并算法保证数据的完整性. 注意 sync() 不仅能存储 QSettings 的变更内容, 也能导入被其他程序修改的内容.
平台特定说明
应用程序的设置存储位置
在 Fallback Mechanism 章节提到, 根据不同的作用域,应用程序及组织名,QSettings 将配置数据存储在多达4个位置. 同样, 假设我们的组织名叫MySoft, 我们的应用程序叫Star Runner.
在 Unix 系统, 如果文件格式是 NativeFormat, 默认存储文件如下:
$HOME/.config/MySoft/Star Runner.conf
(Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.conf
)$HOME/.config/MySoft.conf
(Qt for Embedded Linux:$HOME/Settings/MySoft.conf
)- for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.conf
- for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft.conf
注: 如果没有设置 XDG_CONFIG_DIRS , 默认目录是 /etc/xdg
.
在 macOS 版本 10.2 和 10.3 中, 默认存储文件如下:
$HOME/Library/Preferences/com.MySoft.Star Runner.plist
$HOME/Library/Preferences/com.MySoft.plist
/Library/Preferences/com.MySoft.Star Runner.plist
/Library/Preferences/com.MySoft.plist
在 Windows 系统, NativeFormat 配置被存储在系统注册表的如下位置:
HKEY_CURRENT_USER\Software\MySoft\Star Runner
HKEY_CURRENT_USER\Software\MySoft\OrganizationDefaults
HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
HKEY_LOCAL_MACHINE\Software\MySoft\OrganizationDefaults
注: 在 Windows 系统, 运行在64位系统的 32 位应用程序, 配置被存储在系统注册表的如下位置: HKEY_LOCAL_MACHINE\Software\WOW6432node
.
如果文件格式是 NativeFormat, 配置存储在应用程序目录下的 "Settings/MySoft/Star Runner.conf" .
如果文件格式是 IniFormat, 在 Unix, macOS, 和 iOS 系统, 存储文件如下:
$HOME/.config/MySoft/Star Runner.ini
(Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.ini
)$HOME/.config/MySoft.ini
(Qt for Embedded Linux:$HOME/Settings/MySoft.ini
)- for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.ini
- for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft.ini
Note: 如果没有设置 XDG_CONFIG_DIRS , 默认目录是 /etc/xdg
.
在 Windows 系统, 存储文件如下:
FOLDERID_RoamingAppData\MySoft\Star Runner.ini
FOLDERID_RoamingAppData\MySoft.ini
FOLDERID_ProgramData\MySoft\Star Runner.ini
FOLDERID_ProgramData\MySoft.ini
前缀 FOLDERID_
是通过获取相对路径的Win32 API 函数 SHGetKnownFolderPath()
传递的一个特定 ID列表.
FOLDERID_RoamingAppData
通常指向 C:\Users\User Name\AppData\Roaming
, 也可以通过环境变量 %APPDATA%
获取.
FOLDERID_ProgramData
通常指向 C:\ProgramData
.
如果文件格式是 IniFormat, 配置存储在应用程序目录下的 "Settings/MySoft/Star Runner.ini" .
以 .ini
和 .conf
为后缀的文件可以使用 setPath() 修改路径. 在 Unix, macOS, 和 iOS 系统, 用户可以通过环境变量 XDG_CONFIG_HOME
覆盖路径配置; 详见 setPath() .
读取 INI 和 .plist 文件
有时, 你想在特定的文件或注册路径中存储配置. 如果你想在所有的系统中直接从INI文件读取配置, 那么你可以将文件名作为 QSettings 构造函数的第一个参数传入, 将 QSettings::IniFormat 作为第二个参数. 例如:
QSettings settings("/home/petra/misc/myapp.ini", QSettings::IniFormat);
你可以用 QSettings 对象在文件中存取配置.
在 macOS 和 iOS 系统, 你可以将QSettings::NativeFormat 作为第二个参数, 读写后缀为.plist
的属性列表文件. 例如:
QSettings settings("/Users/petra/misc/myapp.plist", QSettings::NativeFormat);
读写 Windows 注册表
在 Windows 系统, QSettings 让你可以直接在注册表中读取被 QSettings (或支持格式的配置数据, 如.字符串数据) 写入的数据. 这种操作, 可以在 QSettings 的构造函数中传入注册表路径和 QSettings::NativeFormat.
例如:
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office", QSettings::NativeFormat);
在指定的路径下, 所有的注册表项都能通过 QSettings 对象读取 (用斜杠替代反斜杠). 例如:
settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0);
注: 反斜杠被 QSettings 用来给key划分层级. 因此, 你不能读写包含正反斜杠的windows注册表项; 如果你必须这么做, 请使用windows原生API.
读写Windows系统的公共注册项
在 Windows 系统, 注册表项可能有值或者子项. 通过 "Default" 读取默认值, 通过 "." 读取子项:
settings.setValue("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy", "Milkyway"); settings.setValue("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy\\Sun", "OurStar"); settings.value("HKEY_CURRENT_USER\\MySoft\\Star Runner\\Galaxy\\Default"); // returns "Milkyway"
其他系统, "Default" 和 "." 被视作子项.
平台限制
虽然 QSettings 在尽量消除平台间的差异, 但是仍然有些差异需要你在移植应用程序的时候注意:
- Windows 系统的注册表的限制: 一个子键长度不能超过255字符, 一个表项的值不能超过 16,383 字符, 一个键的值长度不能超过 65,535 字符. 解决这些限制的一个方法是采用 IniFormat 替代 NativeFormat 存储设置.
- 在 macOS 和 iOS 系统, allKeys() 会返回适用于所有应用程序的全局设置的key值. 这些key值仅能通过 value() 读取, 但是不能修改. 调用 setFallbacksEnabled(false) 将屏蔽这些全局设置.
- 在 macOS 和 iOS 系统, QSettings 采用CFPreferences API 实现, 这类API使用网络域名, 而不是组织名. 为了统一API接口, QSettings 参照组织名生成一个伪域名 ( 除非这个组织名本身就是一个域名, 例如. OpenOffice.org). 这个算法是在公司名称后面附加 ".com", 并使用连字符替换空格和其他非法字符. 如果你想使用不同的域名, 那么在主函数中调用 QCoreApplication::setOrganizationDomain(), QCoreApplication::setOrganizationName(), 和 QCoreApplication::setApplicationName(), 然后用 QSettings 默认构造函数. 另一个解决方案是使用预处理指令, 如下:
#ifdef Q_OS_MAC QSettings settings("grenoullelogique.fr", "Squash"); #else QSettings settings("Grenoulle Logique", "Squash"); #endif
- 在 macOS 系统, 从10.7(Lion)版本开始, 访问不属于当前用户的设置权限 (i.e. SystemScope) 已经发生编号. 在这个版本之前, 只有管理员权限的用户才能访问这些. 对于 10.7 和 10.8 (Mountain Lion), 只有 root 才能. 然而, 10.9 (Mavericks) 再次做了改变这些规则仅适用于本地格式 (plist files).
参见 QVariant, QSessionManager, Settings Editor Example, 和 Application Example.
成员类型
enum QSettings::Format
这个枚举类型指定 QSettings 的存储格式.
Constant | Value | Description |
---|---|---|
QSettings::NativeFormat | 0 | 使用最适合平台的存储格式. Windows 是系统注册表; macOS 和 iOS 是 CFPreferences API; Unix 是 INI 格式的配置文件. |
QSettings::Registry32Format | 2 | 仅支持Windows: 在64位Windows上运行的64位应用程序显式访问32位系统注册表. 在32位Windows或64位Windows上的32位应用程序中, 这与指定NativeFormat相同. 这个枚举值从 Qt 5.7. 开始 |
QSettings::Registry64Format | 3 | 仅支持Windows: 从64位Windows上运行的32位应用程序显式访问64位系统注册表. 在32位Windows或64位Windows上的64位应用程序中, 这与指定NativeFormat相同. 这个枚举值从 Qt 5.7. 开始 |
QSettings::IniFormat | 1 | 在INI文件中存储. |
QSettings::InvalidFormat | 16 | 调用 registerFormat()返回特定值. |
在 Unix 系统, NativeFormat 和 IniFormat 是一样的, 除非采用不同的文件后缀 (.conf
用于 NativeFormat, .ini
用于 IniFormat).
INI文件格式是windows文件格式, Qt实现全平台支持. 由于缺乏标准, 我们尽量跟随Microsoft定义, 以下内容除外:
- 如果你存储的 QVariant 类型无法转换为 QString (如., QPoint, QRect 和 QSize), Qt 用
@
-based 语法编码类型. 比如:pos = @Point(100 100)
为了最大限度地减少兼容性问题, 任何没有出现在第一位或后面没有Qt类型(
Point
,Rect
,Size
, etc.)的@
被视为普通字符. - 在INI文件中, 虽然反斜杠是一种特殊字符, 但是大部分应用程序不会在文件路径中转义反斜杠 (
\
) :windir = C:\Windows
QSettings 总是将反斜杠视作特殊字符, 并且不会提供读写API.
- INI文件格式对key值语法有些限制. Qt使用
%
作为转移字符. 此外, 如果你存储一个最上级的设置 (key值没有反斜杠, 例如., "someKey"), 这个会出现在INI文件的 "General" 节下. 为了避免覆盖其他的值, 如果你使用 "General/someKey" 作为key值, 这个key值将存储在 "%General" 节下, 禁止 使用 "General" 节. - 遵循理念: 我们应该在可接受的方面保持自由, 在生成的方面保持保守. QSettings 可以读取 Latin-1 编码的INI文件, 但是生成纯粹的 ASCII 文件, 其中非ASCII值会使用标准INI转义字符编码. 调用 setIniCodec() 可以使INI文件可读性更强, 但是会降低兼容性.
参见 registerFormat() and setPath().
typedef QSettings::ReadFunc
定义如下的函数指针:
bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map);
ReadFunc
用于 registerFormat()
, 定义对key/value的读取函数. ReadFunc
应该一次读取所有的选项, 使用 SettingsMap
容器返回.
参见 WriteFunc and registerFormat().
enum QSettings::Scope
这个枚举类型指定配置作用范围.
Constant | Value | Description |
---|---|---|
QSettings::UserScope | 0 | 存储在当前用户的特定位置 (例如., 当前用户的home路径). |
QSettings::SystemScope | 1 | 存储在系统位置, 以便所有用户都能读取相同配置. |
参见 setPath().
typedef QSettings::SettingsMap
Typedef for QMap<QString, QVariant>.
参见 registerFormat().
enum QSettings::Status
下面是状态的可能取值:
Constant | Value | Description |
---|---|---|
QSettings::NoError | 0 | 无错误. |
QSettings::AccessError | 1 | 权限错误 (例如. 试图写一个只读文件). |
QSettings::FormatError | 2 | 格式错误 (例如. 加载一个残缺的INI文件). |
参见 status().
typedef QSettings::WriteFunc
定义如下的函数指针:
bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map);
WriteFunc
用于 registerFormat()
, 定义对key/value的写函数. WriteFunc
仅仅调用一次, 所以一次性写入所有的配置数据.
参见 ReadFunc and registerFormat().
成员函数
QSettings::QSettings(const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR)
Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent.
Example:
QSettings settings("Moose Tech", "Facturo-Pro");
The scope is set to QSettings::UserScope, and the format is set to QSettings::NativeFormat (i.e. calling setDefaultFormat() before calling this constructor has no effect).
参见 setDefaultFormat() and Fallback Mechanism.
QSettings::QSettings(Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR)
Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent.
If scope is QSettings::UserScope, the QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope, the QSettings object ignores user-specific settings and provides access to system-wide settings.
The storage format is set to QSettings::NativeFormat (i.e. calling setDefaultFormat() before calling this constructor has no effect).
If no application name is given, the QSettings object will only access the organization-wide locations.
参见 setDefaultFormat().
QSettings::QSettings(Format format, Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = Q_NULLPTR)
Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent.
If scope is QSettings::UserScope, the QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope, the QSettings object ignores user-specific settings and provides access to system-wide settings.
If format is QSettings::NativeFormat, the native API is used for storing settings. If format is QSettings::IniFormat, the INI format is used.
If no application name is given, the QSettings object will only access the organization-wide locations.
QSettings::QSettings(const QString &fileName, Format format, QObject *parent = Q_NULLPTR)
Constructs a QSettings object for accessing the settings stored in the file called fileName, with parent parent. If the file doesn't already exist, it is created.
If format is QSettings::NativeFormat, the meaning of fileName depends on the platform. On Unix, fileName is the name of an INI file. On macOS and iOS, fileName is the name of a .plist
file. On Windows, fileName is a path in the system registry.
If format is QSettings::IniFormat, fileName is the name of an INI file.
Warning: This function is provided for convenience. It works well for accessing INI or .plist
files generated by Qt, but might fail on some syntaxes found in such files originated by other programs. In particular, be aware of the following limitations:
- QSettings provides no way of reading INI "path" entries, i.e., entries with unescaped slash characters. (This is because these entries are ambiguous and cannot be resolved automatically.)
- In INI files, QSettings uses the
@
character as a metacharacter in some contexts, to encode Qt-specific data types (e.g.,@Rect
), and might therefore misinterpret it when it occurs in pure INI files.
参见 fileName().
QSettings::QSettings(QObject *parent = Q_NULLPTR)
Constructs a QSettings object for accessing settings of the application and organization set previously with a call to QCoreApplication::setOrganizationName(), QCoreApplication::setOrganizationDomain(), and QCoreApplication::setApplicationName().
The scope is QSettings::UserScope and the format is defaultFormat() (QSettings::NativeFormat by default). Use setDefaultFormat() before calling this constructor to change the default format used by this constructor.
The code
QSettings settings("Moose Soft", "Facturo-Pro");
is equivalent to
QCoreApplication::setOrganizationName("Moose Soft"); QCoreApplication::setApplicationName("Facturo-Pro"); QSettings settings;
If QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName() has not been previously called, the QSettings object will not be able to read or write any settings, and status() will return AccessError.
On macOS and iOS, if both a name and an Internet domain are specified for the organization, the domain is preferred over the name. On other platforms, the name is preferred over the domain.
参见 QCoreApplication::setOrganizationName(), QCoreApplication::setOrganizationDomain(), QCoreApplication::setApplicationName(), and setDefaultFormat().
QSettings::~QSettings()
Destroys the QSettings object.
Any unsaved changes will eventually be written to permanent storage.
参见 sync().
QStringList QSettings::allKeys() const
Returns a list of all keys, including subkeys, that can be read using the QSettings object.
Example:
QSettings settings; settings.setValue("fridge/color", QColor(Qt::white)); settings.setValue("fridge/size", QSize(32, 96)); settings.setValue("sofa", true); settings.setValue("tv", false); QStringList keys = settings.allKeys(); // keys: ["fridge/color", "fridge/size", "sofa", "tv"]
If a group is set using beginGroup(), only the keys in the group are returned, without the group prefix:
settings.beginGroup("fridge"); keys = settings.allKeys(); // keys: ["color", "size"]
参见 childGroups() and childKeys().
QString QSettings::applicationName() const
Returns the application name used for storing the settings.
This function was introduced in Qt 4.4.
参见 QCoreApplication::applicationName(), format(), scope(), and organizationName().
void QSettings::beginGroup(const QString &prefix)
Appends prefix to the current group.
The current group is automatically prepended to all keys specified to QSettings. In addition, query functions such as childGroups(), childKeys(), and allKeys() are based on the group. By default, no group is set.
Groups are useful to avoid typing in the same setting paths over and over. For example:
settings.beginGroup("mainwindow"); settings.setValue("size", win->size()); settings.setValue("fullScreen", win->isFullScreen()); settings.endGroup(); settings.beginGroup("outputpanel"); settings.setValue("visible", panel->isVisible()); settings.endGroup();
This will set the value of three settings:
mainwindow/size
mainwindow/fullScreen
outputpanel/visible
Call endGroup() to reset the current group to what it was before the corresponding beginGroup() call. Groups can be nested.
int QSettings::beginReadArray(const QString &prefix)
Adds prefix to the current group and starts reading from an array. Returns the size of the array.
Example:
struct Login { QString userName; QString password; }; QList<Login> logins; ... QSettings settings; int size = settings.beginReadArray("logins"); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); Login login; login.userName = settings.value("userName").toString(); login.password = settings.value("password").toString(); logins.append(login); } settings.endArray();
Use beginWriteArray() to write the array in the first place.
参见 beginWriteArray(), endArray(), and setArrayIndex().
void QSettings::beginWriteArray(const QString &prefix, int size = -1)
Adds prefix to the current group and starts writing an array of size size. If size is -1 (the default), it is automatically determined based on the indexes of the entries written.
If you have many occurrences of a certain set of keys, you can use arrays to make your life easier. For example, let's suppose that you want to save a variable-length list of user names and passwords. You could then write:
struct Login { QString userName; QString password; }; QList<Login> logins; ... QSettings settings; settings.beginWriteArray("logins"); for (int i = 0; i < logins.size(); ++i) { settings.setArrayIndex(i); settings.setValue("userName", list.at(i).userName); settings.setValue("password", list.at(i).password); } settings.endArray();
The generated keys will have the form
logins/size
logins/1/userName
logins/1/password
logins/2/userName
logins/2/password
logins/3/userName
logins/3/password
- ...
To read back an array, use beginReadArray().
参见 beginReadArray(), endArray(), and setArrayIndex().
QStringList QSettings::childGroups() const
Returns a list of all key top-level groups that contain keys that can be read using the QSettings object.
Example:
QSettings settings; settings.setValue("fridge/color", QColor(Qt::white)); settings.setValue("fridge/size", QSize(32, 96)); settings.setValue("sofa", true); settings.setValue("tv", false); QStringList groups = settings.childGroups(); // groups: ["fridge"]
If a group is set using beginGroup(), the first-level keys in that group are returned, without the group prefix.
settings.beginGroup("fridge"); groups = settings.childGroups(); // groups: []
You can navigate through the entire setting hierarchy using childKeys() and childGroups() recursively.
QStringList QSettings::childKeys() const
Returns a list of all top-level keys that can be read using the QSettings object.
Example:
QSettings settings; settings.setValue("fridge/color", QColor(Qt::white)); settings.setValue("fridge/size", QSize(32, 96)); settings.setValue("sofa", true); settings.setValue("tv", false); QStringList keys = settings.childKeys(); // keys: ["sofa", "tv"]
If a group is set using beginGroup(), the top-level keys in that group are returned, without the group prefix:
settings.beginGroup("fridge"); keys = settings.childKeys(); // keys: ["color", "size"]
You can navigate through the entire setting hierarchy using childKeys() and childGroups() recursively.
参见 childGroups() and allKeys().
void QSettings::clear()
Removes all entries in the primary location associated to this QSettings object.
Entries in fallback locations are not removed.
If you only want to remove the entries in the current group(), use remove("") instead.
参见 remove() and setFallbacksEnabled().
bool QSettings::contains(const QString &key) const
Returns true
if there exists a setting called key; returns false otherwise.
If a group is set using beginGroup(), key is taken to be relative to that group.
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.
[static]
Format QSettings::defaultFormat()
Returns default file format used for storing settings for the QSettings(QObject *) constructor. If no default format is set, QSettings::NativeFormat is used.
This function was introduced in Qt 4.4.
参见 setDefaultFormat() and format().
void QSettings::endArray()
Closes the array that was started using beginReadArray() or beginWriteArray().
参见 beginReadArray() and beginWriteArray().
void QSettings::endGroup()
Resets the group to what it was before the corresponding beginGroup() call.
Example:
settings.beginGroup("alpha"); // settings.group() == "alpha" settings.beginGroup("beta"); // settings.group() == "alpha/beta" settings.endGroup(); // settings.group() == "alpha" settings.endGroup(); // settings.group() == ""
参见 beginGroup() and group().
[virtual protected]
bool QSettings::event(QEvent *event)
Reimplemented from QObject::event().
bool QSettings::fallbacksEnabled() const
Returns true
if fallbacks are enabled; returns false
otherwise.
By default, fallbacks are enabled.
参见 setFallbacksEnabled().
QString QSettings::fileName() const
Returns the path where settings written using this QSettings object are stored.
On Windows, if the format is QSettings::NativeFormat, the return value is a system registry path, not a file path.
参见 isWritable() and format().
Format QSettings::format() const
Returns the format used for storing the settings.
This function was introduced in Qt 4.4.
参见 defaultFormat(), fileName(), scope(), organizationName(), and applicationName().
QString QSettings::group() const
Returns the current group.
参见 beginGroup() and endGroup().
QTextCodec *QSettings::iniCodec() const
Returns the codec that is used for accessing INI files. By default, no codec is used, so a null pointer is returned.
This function was introduced in Qt 4.5.
参见 setIniCodec().
bool QSettings::isWritable() const
Returns true
if settings can be written using this QSettings object; returns false
otherwise.
One reason why isWritable() might return false is if QSettings operates on a read-only file.
Warning: This function is not perfectly reliable, because the file permissions can change at any time.
参见 fileName(), status(), and sync().
QString QSettings::organizationName() const
Returns the organization name used for storing the settings.
This function was introduced in Qt 4.4.
参见 QCoreApplication::organizationName(), format(), scope(), and applicationName().
[static]
Format QSettings::registerFormat(const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive)
Registers a custom storage format. On success, returns a special Format value that can then be passed to the QSettings constructor. On failure, returns InvalidFormat.
The extension is the file extension associated to the format (without the '.').
The readFunc and writeFunc parameters are pointers to functions that read and write a set of key/value pairs. The QIODevice parameter to the read and write functions is always opened in binary mode (i.e., without the QIODevice::Text flag).
The caseSensitivity parameter specifies whether keys are case sensitive or not. This makes a difference when looking up values using QSettings. The default is case sensitive.
By default, if you use one of the constructors that work in terms of an organization name and an application name, the file system locations used are the same as for IniFormat. Use setPath() to specify other locations.
Example:
bool readXmlFile(QIODevice &device, QSettings::SettingsMap &map); bool writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map); int main(int argc, char *argv[]) { const QSettings::Format XmlFormat = QSettings::registerFormat("xml", readXmlFile, writeXmlFile); QSettings settings(XmlFormat, QSettings::UserScope, "MySoft", "Star Runner"); ... }
Note: This function is thread-safe
This function was introduced in Qt 4.1.
参见 setPath().
void QSettings::remove(const QString &key)
Removes the setting key and any sub-settings of key.
Example:
QSettings settings; settings.setValue("ape"); settings.setValue("monkey", 1); settings.setValue("monkey/sea", 2); settings.setValue("monkey/doe", 4); settings.remove("monkey"); QStringList keys = settings.allKeys(); // keys: ["ape"]
Be aware that if one of the fallback locations contains a setting with the same key, that setting will be visible after calling remove().
If key is an empty string, all keys in the current group() are removed. For example:
QSettings settings; settings.setValue("ape"); settings.setValue("monkey", 1); settings.setValue("monkey/sea", 2); settings.setValue("monkey/doe", 4); settings.beginGroup("monkey"); settings.remove(""); settings.endGroup(); QStringList keys = settings.allKeys(); // keys: ["ape"]
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.
参见 setValue(), value(), and contains().
Scope QSettings::scope() const
Returns the scope used for storing the settings.
This function was introduced in Qt 4.4.
参见 format(), organizationName(), and applicationName().
void QSettings::setArrayIndex(int i)
Sets the current array index to i. Calls to functions such as setValue(), value(), remove(), and contains() will operate on the array entry at that index.
You must call beginReadArray() or beginWriteArray() before you can call this function.
[static]
void QSettings::setDefaultFormat(Format format)
Sets the default file format to the given format, which is used for storing settings for the QSettings(QObject *) constructor.
If no default format is set, QSettings::NativeFormat is used. See the documentation for the QSettings constructor you are using to see if that constructor will ignore this function.
This function was introduced in Qt 4.4.
参见 defaultFormat() and format().
void QSettings::setFallbacksEnabled(bool b)
Sets whether fallbacks are enabled to b.
By default, fallbacks are enabled.
参见 fallbacksEnabled().
void QSettings::setIniCodec(QTextCodec *codec)
Sets the codec for accessing INI files (including .conf
files on Unix) to codec. The codec is used for decoding any data that is read from the INI file, and for encoding any data that is written to the file. By default, no codec is used, and non-ASCII characters are encoded using standard INI escape sequences.
Warning: The codec must be set immediately after creating the QSettings object, before accessing any data.
This function was introduced in Qt 4.5.
参见 iniCodec().
void QSettings::setIniCodec(const char *codecName)
This is an overloaded function.
Sets the codec for accessing INI files (including .conf
files on Unix) to the QTextCodec for the encoding specified by codecName. Common values for codecName
include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.
This function was introduced in Qt 4.5.
参见 QTextCodec::codecForName().
[static]
void QSettings::setPath(Format format, Scope scope, const QString &path)
Sets the path used for storing settings for the given format and scope, to path. The format can be a custom format.
The table below summarizes the default values:
Platform | Format | Scope | Path |
---|---|---|---|
Windows | IniFormat | UserScope | FOLDERID_RoamingAppData |
SystemScope | FOLDERID_ProgramData | ||
Unix | NativeFormat, IniFormat | UserScope | $HOME/.config |
SystemScope | /etc/xdg | ||
Qt for Embedded Linux | NativeFormat, IniFormat | UserScope | $HOME/Settings |
SystemScope | /etc/xdg | ||
macOS and iOS | IniFormat | UserScope | $HOME/.config |
SystemScope | /etc/xdg |
The default UserScope paths on Unix, macOS, and iOS ($HOME/.config
or $HOME/Settings) can be overridden by the user by setting the XDG_CONFIG_HOME
environment variable. The default SystemScope paths on Unix, macOS, and iOS (/etc/xdg
) can be overridden when building the Qt library using the configure
script's -sysconfdir
flag (see QLibraryInfo for details).
Setting the NativeFormat paths on Windows, macOS, and iOS has no effect.
Warning: This function doesn't affect existing QSettings objects.
This function was introduced in Qt 4.1.
参见 registerFormat().
void QSettings::setValue(const QString &key, const QVariant &value)
Sets the value of setting key to value. If the key already exists, the previous value is overwritten.
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.
Example:
QSettings settings; settings.setValue("interval", 30); settings.value("interval").toInt(); // returns 30 settings.setValue("interval", 6.55); settings.value("interval").toDouble(); // returns 6.55
参见 value(), remove(), and contains().
Status QSettings::status() const
Returns a status code indicating the first error that was met by QSettings, or QSettings::NoError if no error occurred.
Be aware that QSettings delays performing some operations. For this reason, you might want to call sync() to ensure that the data stored in QSettings is written to disk before calling status().
参见 sync().
void QSettings::sync()
Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application.
This function is called automatically from QSettings's destructor and by the event loop at regular intervals, so you normally don't need to call it yourself.
参见 status().
QVariant QSettings::value(const QString &key, const QVariant &defaultValue = QVariant()) const
Returns the value for setting key. If the setting doesn't exist, returns defaultValue.
If no default value is specified, a default QVariant is returned.
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.
Example:
QSettings settings; settings.setValue("animal/snake", 58); settings.value("animal/snake", 1024).toInt(); // returns 58 settings.value("animal/zebra", 1024).toInt(); // returns 1024 settings.value("animal/zebra").toInt(); // returns 0