QSettings 类

QSettings class provides persistent platform-independent application settings. 更多...

头: #include <QSettings>
qmake: QT += core
继承: QObject

注意: 此类的所有函数 可重入 .

注意: 这些函数也是 thread-safe :

  • 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 () const
QString group () const
QTextCodec * iniCodec () const
bool isWritable () const
QString organizationName () const
void remove (const QString & key )
作用域 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

静态公共成员

格式 defaultFormat ()
格式 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 )

重实现保护函数

virtual bool event (QEvent * event )

额外继承成员

详细描述

QSettings class provides persistent platform-independent application settings.

用户通常期望应用程序跨会话记住其设置 (窗口大小和位置、选项、等等)。此信息常存储在 Windows 的系统注册表中,macOS 和 iOS 的特性列表文件中。在缺乏标准的 Unix 系统,许多应用程序 (包括 KDE 应用程序) 使用 INI 文本文件。

QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports 自定义存储格式 .

QSettings 's API is based on QVariant ,允许保存大多数基于值的类型,譬如 QString , QRect ,和 QImage ,采用最少努力。

若需要的全是基于内存的非持久性结构,请考虑使用 QMap < QString , QVariant > 代替。

基本用法

当创建 QSettings object, you must pass the name of your company or organization as well as the name of your application. For example, if your product is called Star Runner and your company is called MySoft, you would construct the QSettings object as follows:

    QSettings settings("MySoft", "Star Runner");
					

QSettings objects can be created either on the stack or on the heap (i.e. using new ). Constructing and destroying a QSettings object is very fast.

若使用 QSettings from many places in your application, you might want to specify the organization name and the application name using QCoreApplication::setOrganizationName () 和 QCoreApplication::setApplicationName (), and then use the default QSettings 构造函数:

    QCoreApplication::setOrganizationName("MySoft");
    QCoreApplication::setOrganizationDomain("mysoft.com");
    QCoreApplication::setApplicationName("Star Runner");
    ...
    QSettings settings;
					

(这里,我们还指定了组织的 Internet 域。当被设置时,Internet 域在 macOS 和 iOS 上被用于代替组织名称,因为 macOS 和 iOS 应用程序按照惯例会使用 Internet 域去标识它们自己。若未设置域,则从组织名称派生虚假域。见 特定平台注意事项 了解细节。)

QSettings stores settings. Each setting consists of a QString 指定设置的名称 ( key ) 和 QVariant 存储键关联数据。要写入设置,使用 setValue ()。例如:

    settings.setValue("editor/wrapMargin", 68);
					

若已经存在具有相同键的设置,则现有值被新值所覆写。为提高效率,改变可能不会被立即保存到永久存储。(可以始终调用 sync () 去提交改变。)

可以获取设置的值使用 value ():

    int margin = settings.value("editor/wrapMargin").toInt();
					

If there is no setting with the specified name, QSettings returns a null QVariant (其可以被转换成整数 0)。可以指定另一默认值通过把第 2 自变量传递给 value ():

    int margin = settings.value("editor/wrapMargin", 80).toInt();
					

要测试给定键是否存在,调用 contains ()。要移除键关联设置,调用 remove ()。要获得所有键的列表,调用 allKeys ()。要移除所有键,调用 clear ().

QVariant 和 GUI 类型

因为 QVariant 属于 Qt Core 模块,它不能提供数据类型转换函数,如 QColor , QImage ,和 QPixmap ,其属于 Qt GUI。换句话说,没有 toColor() , toImage() ,或 toPixmap() 函数在 QVariant .

相反,可以使用 QVariant::value () or the qVariantValue() template function. For example:

QSettings settings("MySoft", "Star Runner");
QColor color = settings.value("DataPump/bgcolor").value<QColor>();
					

反向转换 (如,从 QColor to QVariant ) 对于所有支持数据类型是自动通过 QVariant ,包括 GUI 相关类型:

QSettings settings("MySoft", "Star Runner");
QColor color = palette().background().color();
settings.setValue("DataPump/bgcolor", color);
					

自定义类型注册采用 qRegisterMetaType () 和 qRegisterMetaTypeStreamOperators () can be stored using QSettings .

区间和键句法

设置键可以包含任何 Unicode 字符。Windows 注册表和 INI 文件使用不区分大小写的键,而在 macOS 和 iOS 上的 CFPreferences API 使用区分大小写的键。为避免可移植性问题,遵循这些简单规则:

  1. 始终使用相同大小写,引用相同键。例如,若在代码中某个地方按 text fonts 引用键,就不要在其它地方按 Text Fonts 引用它。
  2. 避免键名称恒等,除大小写外。例如,若拥有的键称为 MainWindow ,就不要试着把另一个键另存为 mainwindow。
  3. Do not use slashes ('/' and '\') in section or key names; the backslash character is used to separate sub keys (see below). On windows '\' are converted by QSettings to '/', which makes them identical.

可以使用 / 字符作为分隔符来形成分层键,类似 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 (),因此,大多数函数的行为改变。组可以被递归设置。

In addition to groups, QSettings also supports an "array" concept. See beginReadArray () 和 beginWriteArray () 了解细节。

回退机制

Let's assume that you have created a QSettings object with the organization name MySoft and the application name Star Runner. When you look up a value, up to four locations are searched in that order:

  1. 为 Star Runner 应用程序的特定用户位置
  2. 由 MySoft 为所有应用程序的特定用户位置
  3. 为 Star Runner 应用程序的系统范围位置
  4. 由 MySoft 为所有应用程序的系统范围位置

(见 特定平台注意事项 了解在 Qt 支持的不同平台,这些位置的有关信息。)

若在第一位置找不到键,则在第二位置继续搜索,依此类推。这使您能够存储系统范围 (或组织范围) 设置,并在每用户 (或每应用程序) 的基础上覆盖它们。要关闭此机制,调用 setFallbacksEnabled (false).

虽然来自所有 4 个位置的键都可用于读取,但仅第一个文件 (为手中应用程序的特定用户位置) 可写访问。要写入任何其它文件,省略应用程序名称和/或指定 QSettings::SystemScope (而不是 QSettings::UserScope ,默认)。

让我们看下范例:

    QSettings obj1("MySoft", "Star Runner");
    QSettings obj2("MySoft");
    QSettings obj3(QSettings::SystemScope, "MySoft", "Star Runner");
    QSettings obj4(QSettings::SystemScope, "MySoft");
					

The table below summarizes which QSettings objects access which location. " X " means that the location is the main location associated to the QSettings object and is used both for reading and for writing; "o" means that the location is used as a fallback when reading.

位置 obj1 obj2 obj3 obj4
1. 用户、应用程序 X
2. 用户、组织 o X
3. 系统、应用程序 o X
4. 系统、组织 o o o X

这种机制的妙处是它工作于由 Qt 支持的所有平台,且仍然给予很大灵活性,不要求指定任何文件名 (或注册表路径)。

若想要在所有平台使用 INI 文件而不是本机 API,可以传递 QSettings::IniFormat as the first argument to the QSettings constructor, followed by the scope, the organization name, and the application name:

    QSettings settings(QSettings::IniFormat, QSettings::UserScope,
                       "MySoft", "Star Runner");
					

设置编辑器 范例允许您试验不同设置位置,及启用或禁用回退。

还原 GUI 应用程序的状态

QSettings is often used to store the state of a GUI application. The following example illustrates how to use QSettings to save and restore the geometry of an application's main window.

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();
}
					

窗口几何体 了解为什么更好的论述,调用 QWidget::resize () 和 QWidget::move () 而不是 QWidget::setGeometry () 去还原窗口几何体。

readSettings() and writeSettings() 函数必须从主窗口的构造函数调用,关闭事件处理程序如下所示:

MainWindow::MainWindow()
{
    ...
    readSettings();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    if (userReallyWantsToQuit()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}
					

应用程序 example for a self-contained example that uses QSettings .

同时从多个线程 (或进程) 访问设置

QSettings is 可重入 . This means that you can use distinct QSettings object in different threads simultaneously. This guarantee stands even when the QSettings objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through one QSettings object, the change will immediately be visible in any other QSettings objects that operate on the same location and that live in the same process.

QSettings can safely be used from different processes (which can be different instances of your application running at the same time or different applications altogether) to read and write to the same system locations. It uses advisory file locking and a smart merging algorithm to ensure data integrity. Note that sync () imports changes made by other processes (in addition to writing the changes from this QSettings ).

特定平台注意事项

存储应用程序设置的位置

作为提及在 回退机制 section, QSettings stores settings for an application in up to four locations, depending on whether the settings are user-specific or system-wide and whether the settings are application-specific or organization-wide. For simplicity, we're assuming the organization is called MySoft and the application is called Star Runner.

在 Unix 系统,若文件格式为 NativeFormat ,默认使用下列文件:

  1. $HOME/.config/MySoft/Star Runner.conf (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.conf )
  2. $HOME/.config/MySoft.conf (Qt for Embedded Linux: $HOME/Settings/MySoft.conf )
  3. 对于每目录 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.conf
  4. 对于每目录 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft.conf

注意: 若 XDG_CONFIG_DIRS 未设置,使用 /etc/xdg 默认值。

在 macOS 第 10.2 和 10.3 版,默认使用这些文件:

  1. $HOME/Library/Preferences/com.MySoft.Star Runner.plist
  2. $HOME/Library/Preferences/com.MySoft.plist
  3. /Library/Preferences/com.MySoft.Star Runner.plist
  4. /Library/Preferences/com.MySoft.plist

在 Windows, NativeFormat 设置存储在下列注册表路径:

  1. HKEY_CURRENT_USER\Software\MySoft\Star Runner
  2. HKEY_CURRENT_USER\Software\MySoft\OrganizationDefaults
  3. HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
  4. HKEY_LOCAL_MACHINE\Software\MySoft\OrganizationDefaults

注意: 在 Windows,对于运行在 WOW64 模式下的 32 位程序,设置存储在下列注册表路径: HKEY_LOCAL_MACHINE\Software\WOW6432node .

若文件格式为 NativeFormat ,这是 Settings/MySoft/Star Runner.conf 在应用程序主目录下。

若文件格式为 IniFormat ,在 Unix、macOS 和 iOS 使用下列文件:

  1. $HOME/.config/MySoft/Star Runner.ini (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.ini )
  2. $HOME/.config/MySoft.ini (Qt for Embedded Linux: $HOME/Settings/MySoft.ini )
  3. 对于每目录 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.ini
  4. 对于每目录 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft.ini

注意: 若 XDG_CONFIG_DIRS 未设置,使用 /etc/xdg 默认值。

在 Windows,使用下列文件:

  1. FOLDERID_RoamingAppData\MySoft\Star Runner.ini
  2. FOLDERID_RoamingAppData\MySoft.ini
  3. FOLDERID_ProgramData\MySoft\Star Runner.ini
  4. FOLDERID_ProgramData\MySoft.ini

标识符加前缀通过 FOLDERID_ 是要被传递给 Win32 API 函数的特殊项 ID 列表 SHGetKnownFolderPath() 以获取相应路径。

FOLDERID_RoamingAppData 通常指向 C:\Users\ User Name \AppData\Roaming ,也可展示通过环境变量 %APPDATA% .

FOLDERID_ProgramData 通常指向 C:\ProgramData .

若文件格式为 IniFormat ,这是 Settings/MySoft/Star Runner.ini 在应用程序的主目录下。

.ini and .conf 文件路径可以被改变,使用 setPath ()。在 Unix、macOS 和 iOS,用户可以覆盖它们通过设置 XDG_CONFIG_HOME 环境变量;见 setPath () 了解细节。

直接访问 INI 和 .plist 文件

Sometimes you do want to access settings stored in a specific file or registry path. On all platforms, if you want to read an INI file directly, you can use the QSettings constructor that takes a file name as first argument and pass QSettings::IniFormat 作为第 2 自变量。例如:

QSettings settings("/home/petra/misc/myapp.ini",
                   QSettings::IniFormat);
					

You can then use the QSettings object to read and write settings in the file.

在 macOS 和 iOS,可以访问特性列表 .plist 文件通过传递 QSettings::NativeFormat 作为第 2 自变量。例如:

QSettings settings("/Users/petra/misc/myapp.plist",
                   QSettings::NativeFormat);
					

直接访问 Windows 注册表

在 Windows, QSettings lets you access settings that have been written with QSettings (or settings in a supported format, e.g., string data) in the system registry. This is done by constructing a QSettings object with a path in the registry and QSettings::NativeFormat .

例如:

QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office",
                   QSettings::NativeFormat);
					

All the registry entries that appear under the specified path can be read or written through the QSettings object as usual (using forward slashes instead of backslashes). For example:

settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0);
					

Note that the backslash character is, as mentioned, used by QSettings to separate subkeys. As a result, you cannot read or write windows registry entries that contain slashes or backslashes; you should use a native windows API if you need to do so.

访问 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"
					

在 Windows 外的其他平台,Default 和 . 将被视为常规子键。

平台的局限性

While QSettings attempts to smooth over the differences between the different supported platforms, there are still a few differences that you should be aware of when porting your application:

  • Windows 系统注册表有以下限制:子键不能超过 255 个字符,条目的值不能超过 16,383 个字符,所有键的值不能超过 65,535 个字符。解决这些局限性的办法是存储设置使用 IniFormat 而不是 NativeFormat .
  • On Windows, when the Windows system registry is used, QSettings does not preserve the original type of the value. Therefore, the type of the value might change when a new value is set. For example, a value with type REG_EXPAND_SZ 将改变为 REG_SZ .
  • 在 macOS 和 iOS, allKeys () 将为应用于所有应用程序的全局设置返回一些额外键。这些键可以被读取使用 value () 但无法改变,只有阴影。调用 setFallbacksEnabled (false) 将隐藏这些全局设置。
  • On macOS and iOS, the CFPreferences API used by QSettings expects Internet domain names rather than organization names. To provide a uniform API, QSettings derives a fake domain name from the organization name (unless the organization name already is a domain name, e.g. OpenOffice.org). The algorithm appends ".com" to the company name and replaces spaces and other illegal characters with hyphens. If you want to specify a different domain name, call QCoreApplication::setOrganizationDomain (), QCoreApplication::setOrganizationName (),和 QCoreApplication::setApplicationName () 在您的 main() function and then use the default QSettings constructor. Another solution is to use preprocessor directives, for example:
    #ifdef Q_OS_MAC
        QSettings settings("grenoullelogique.fr", "Squash");
    #else
        QSettings settings("Grenoulle Logique", "Squash");
    #endif
    							
  • 在 macOS,访问不属于当前用户的设置的权限 (即 SystemScope ) 已于 10.7 (狮子) 版改变。在该版本之前,有 admin (管理员) 权限的用户可以访问这些。对于 10.7 和 10.8 (山狮) 版,只有 root 可以。然而,10.9 (小牛队) 版再次改变此规则,但只针对本机格式 (plist 文件)。

另请参阅 QVariant , QSessionManager , 设置编辑器范例 ,和 应用程序范例 .

成员类型文档编制

enum QSettings:: Format

此枚举类型指定存储格式,用于 QSettings .

常量 描述
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 Store the settings in INI files.
QSettings::InvalidFormat 16 特殊值的返回通过 registerFormat ().

在 Unix,NativeFormat 和 IniFormat 意味着相同事情,除文件扩展名不同外 ( .conf 为 NativeFormat, .ini 为 IniFormat)。

INI 文件格式是在所有平台 Qt 所支持的 Windows 文件格式。在缺乏 INI 标准的情况下,我们试着遵循 Microsoft 做法,但有以下例外:

  • 若存储类型 QVariant 无法转换为 QString (如, QPoint , QRect ,和 QSize ),Qt 使用 @ 基句法以编码类型。例如:
    pos = @Point(100 100)
    							

    为最小化兼容性问题,任何 @ 未出现在值第一位置或之后未紧跟 Qt 类型 ( Point , Rect , Size ,等) 被视为正常字符。

  • 尽管反斜杠是 INI 文件中的特殊字符,但大多数 Windows 应用程序不转义反斜杠 ( \ ) 在文件路径:
    windir = C:\Windows
    							

    QSettings 始终视反斜杠为特殊字符,且不提供用于读取或写入这种条目的 API。

  • INI 文件格式对键句法有严格限定。Qt 要解决这是通过使用 % 作为键中转义字符。此外,若保存顶层设置 (其中不带斜线的键,如 someKey),它将出现在 INI 文件的 General 区间。为避免覆盖其它键,若使用如 General/someKey 的这种键保存某些事情,键将位于 %General 区间, not 在 General 区间。
  • 遵循应该在接受的东西上是自由派,而在产生的东西上是保守派的哲学, QSettings 将接受 Latin-1 编码 INI 文件,但生成纯 ASCII 文件,使用标准 INI 转义序列编码其中的非 ASCII 值。要使 INI 文件更可读 (但潜在不太兼容),调用 setIniCodec ().

另请参阅 registerFormat () 和 setPath ().

typedef QSettings:: ReadFunc

Typedef 为指向采用以下签名的函数指针:

bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map);
					

ReadFunc 用于 registerFormat() 作为指向读取一组键/值对的函数指针。 ReadFunc 应一次性读取所有选项,并返回所有设置在 SettingsMap 容器,其最初为空。

另请参阅 WriteFunc and registerFormat ().

enum QSettings:: Scope

此枚举指定设置是具体用户,还是由同一系统的所有用户共享。

常量 描述
QSettings::UserScope 0 将设置存储到当前用户的特定位置 (如:在用户主目录中)。
QSettings::SystemScope 1 将设置存储在全局位置,以便同一计算机中的所有用户访问相同设置集。

另请参阅 setPath ().

typedef QSettings:: SettingsMap

Typedef 为 QMap < QString , QVariant >.

另请参阅 registerFormat ().

enum QSettings:: Status

下列状态值是可能的:

常量 描述
QSettings::NoError 0 没有出现错误。
QSettings::AccessError 1 发生访问错误 (如:试着写入只读文件)。
QSettings::FormatError 2 发生格式错误 (如:加载畸形 INI 文件)。

另请参阅 status ().

typedef QSettings:: WriteFunc

Typedef 为指向采用以下签名的函数指针:

bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map);
					

WriteFunc 用于 registerFormat() 作为指向写入一组键/值对的函数指针。 WriteFunc is only called once, so you need to output the settings in one go.

另请参阅 ReadFunc and registerFormat ().

成员函数文档编制

QSettings:: QSettings (const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

构造 QSettings object for accessing settings of the application called application 从组织称为 organization ,和采用父级 parent .

范例:

QSettings settings("Moose Tech", "Facturo-Pro");
					

作用域设置为 QSettings::UserScope ,和格式设置为 QSettings::NativeFormat (即:调用 setDefaultFormat () 在调用此构造函数不起作用之前)。

另请参阅 setDefaultFormat () 和 回退机制 .

QSettings:: QSettings ( 作用域 scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

构造 QSettings object for accessing settings of the application called application 从组织称为 organization ,和采用父级 parent .

scope is QSettings::UserScope QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope QSettings object ignores user-specific settings and provides access to system-wide settings.

存储格式被设为 QSettings::NativeFormat (即:调用 setDefaultFormat () 在调用此构造函数不起作用之前)。

If no application name is given, the QSettings object will only access the organization-wide locations .

另请参阅 setDefaultFormat ().

QSettings:: QSettings ( Format format , 作用域 scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

构造 QSettings object for accessing settings of the application called application 从组织称为 organization ,和采用父级 parent .

scope is QSettings::UserScope QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope QSettings object ignores user-specific settings and provides access to system-wide settings.

format is QSettings::NativeFormat ,本机 API 用于存储设置。若 format is QSettings::IniFormat ,使用 INI 格式。

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)

构造 QSettings object for accessing the settings stored in the file called fileName ,采用父级 parent 。若文件不存在,创建它。

format is QSettings::NativeFormat ,含义对于 fileName 从属平台。在 Unix, fileName 是 INI 文件的名称。在 macOS 和 iOS, fileName 是名称对于 .plist 文件。在 Windows, fileName 是系统注册表路径。

format is QSettings::IniFormat , fileName 是 INI 文件的名称。

警告: 此函数为方便起见提供。它能很好地访问 INI 或 .plist 文件生成通过 Qt,但可能失败当在发源于其它程序的这种文件中发现某些句法时。尤其,要意识到以下局限性:

  • 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 使用 @ 字符作某些上下文元字符,以编码 Qt 特定数据类型 (如 @Rect ),因此,可能被误解当它出现在纯 INI 文件中时。

另请参阅 fileName ().

QSettings:: QSettings ( QObject * parent = Q_NULLPTR)

构造 QSettings object for accessing settings of the application and organization set previously with a call to QCoreApplication::setOrganizationName (), QCoreApplication::setOrganizationDomain (),和 QCoreApplication::setApplicationName ().

作用域是 QSettings::UserScope 和格式为 defaultFormat () ( QSettings::NativeFormat 默认情况下)。使用 setDefaultFormat () 在调用此构造函数之前去更改用于此构造函数的默认格式。

代码

QSettings settings("Moose Soft", "Facturo-Pro");
					

相当于

QCoreApplication::setOrganizationName("Moose Soft");
QCoreApplication::setApplicationName("Facturo-Pro");
QSettings settings;
					

QCoreApplication::setOrganizationName () 和 QCoreApplication::setApplicationName () has not been previously called, the QSettings object will not be able to read or write any settings, and status () 会返回 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 (),和 setDefaultFormat ().

QSettings:: ~QSettings ()

销毁 QSettings 对象。

任何未保存的改变最后被写入永久存储。

另请参阅 sync ().

QStringList QSettings:: allKeys () const

返回所有键的列表 (包括子键),可以被读取使用 QSettings 对象。

范例:

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"]
					

若设置组使用 beginGroup (),仅返回组中的键,不带组前缀:

settings.beginGroup("fridge");
keys = settings.allKeys();
// keys: ["color", "size"]
					

另请参阅 childGroups () 和 childKeys ().

QString QSettings:: applicationName () const

返回用于存储设置的应用程序名称。

该函数在 Qt 4.4 引入。

另请参阅 QCoreApplication::applicationName (), format (), scope (),和 organizationName ().

void QSettings:: beginGroup (const QString & prefix )

追加 prefix 到当前组。

当前组自动前置所有指定键到 QSettings 。此外,查询函数譬如 childGroups (), childKeys (),和 allKeys () 都是基于组的。默认情况下,未设置组。

组对避免一遍又一遍地键入相同设置路径很有用。例如:

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();
					

这将设置 3 个设置值:

  • mainwindow/size
  • mainwindow/fullScreen
  • outputpanel/visible

调用 endGroup () 以将当前组重置到调用相应 beginGroup() 之前的状态。组可以嵌套。

另请参阅 endGroup () 和 group ().

int QSettings:: beginReadArray (const QString & prefix )

添加 prefix 到当前组并从数组开始读取。返回数组的大小。

范例:

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();
					

使用 beginWriteArray () to write the array in the first place.

另请参阅 beginWriteArray (), endArray (),和 setArrayIndex ().

void QSettings:: beginWriteArray (const QString & prefix , int size = -1)

添加 prefix 到当前组并开始写入数组大小 size 。若 size 为 -1 (默认),它是基于所写条目的索引自动确定的。

若某组键多次出现,则可以使用数组来让您的生活变得更轻松。例如,假设想要保存用户名和口令的可变长度列表。那么可以写:

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();
					

生成键将拥有形式

  • logins/size
  • logins/1/userName
  • logins/1/password
  • logins/2/userName
  • logins/2/password
  • logins/3/userName
  • logins/3/password
  • ...

要读回数组,使用 beginReadArray ().

另请参阅 beginReadArray (), endArray (),和 setArrayIndex ().

QStringList QSettings:: childGroups () const

返回包含可读取键的所有键顶层组的列表,读取使用 QSettings 对象。

范例:

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"]
					

若设置组使用 beginGroup (),返回该组中的首级键,不带组前缀。

settings.beginGroup("fridge");
groups = settings.childGroups();
// groups: []
					

可以导航透过整个设置层次结构使用 childKeys () 和 childGroups() 递归。

另请参阅 childKeys () 和 allKeys ().

QStringList QSettings:: childKeys () const

返回所有顶层键的列表,可以被读取使用 QSettings 对象。

范例:

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"]
					

若设置组使用 beginGroup (),仅返回组中的顶层键,不带组前缀:

settings.beginGroup("fridge");
keys = settings.childKeys();
// keys: ["color", "size"]
					

可以导航透过整个设置层次结构使用 childKeys() 和 childGroups () 递归。

另请参阅 childGroups () 和 allKeys ().

void QSettings:: clear ()

移除首要位置中的所有条目,关联此 QSettings 对象。

不移除回退位置条目。

若只想移除的条目在当前 group (),使用 remove("") 代替。

另请参阅 remove () 和 setFallbacksEnabled ().

bool QSettings:: contains (const QString & key ) const

返回 true 若存在设置被称为 key ;否则返回 false。

若设置组使用 beginGroup (), key 被认为是相对于该组的。

注意:Windows 注册表和 INI 文件使用不区分大小写的键,而 macOS 和 iOS 的 CFPreferences API 使用区分大小写的键。要避免可移植性问题,见 区间和键句法 规则。

另请参阅 value () 和 setValue ().

[static] Format QSettings:: defaultFormat ()

返回用于存储设置的默认文件格式为 QSettings ( QObject *) 构造函数。若未设置默认格式, QSettings::NativeFormat 的使用。

该函数在 Qt 4.4 引入。

另请参阅 setDefaultFormat () 和 format ().

void QSettings:: endArray ()

关闭已启动数组使用 beginReadArray () 或 beginWriteArray ().

另请参阅 beginReadArray () 和 beginWriteArray ().

void QSettings:: endGroup ()

重置组状态先前的相应 beginGroup () 调用。

范例:

settings.beginGroup("alpha");
// settings.group() == "alpha"
settings.beginGroup("beta");
// settings.group() == "alpha/beta"
settings.endGroup();
// settings.group() == "alpha"
settings.endGroup();
// settings.group() == ""
					

另请参阅 beginGroup () 和 group ().

[virtual protected] bool QSettings:: event ( QEvent * event )

重实现自 QObject::event ().

bool QSettings:: fallbacksEnabled () const

返回 true 若回退被启用;返回 false 否则。

默认情况下,回退是启用的。

另请参阅 setFallbacksEnabled ().

QString QSettings:: fileName () const

返回写入设置的路径,使用此 QSettings 对象存储。

在 Windows,若格式为 QSettings::NativeFormat ,返回值是系统注册表路径,而非文件路径。

另请参阅 isWritable () 和 format ().

Format QSettings:: format () const

返回用于存储设置的格式。

该函数在 Qt 4.4 引入。

另请参阅 defaultFormat (), fileName (), scope (), organizationName (),和 applicationName ().

QString QSettings:: group () const

返回当前组。

另请参阅 beginGroup () 和 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.

该函数在 Qt 4.5 引入。

另请参阅 setIniCodec ().

bool QSettings:: isWritable () const

返回 true 若设置可以写入使用此 QSettings 对象;返回 false 否则。

为什么 isWritable() 可能返回 false 的原因之一是若 QSettings 运转于只读文件。

警告: 此函数并不完美可靠,因为文件权限可以随时改变。

另请参阅 fileName (), status (),和 sync ().

QString QSettings:: organizationName () const

返回用于存储设置的组织名称。

该函数在 Qt 4.4 引入。

另请参阅 QCoreApplication::organizationName (), format (), scope (),和 applicationName ().

[static] Format QSettings:: registerFormat (const QString & extension , ReadFunc readFunc , WriteFunc writeFunc , Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive)

注册自定义存储格式。当成功时,返回特殊格式值,然后将其传递给 QSettings 构造函数。当故障时,返回 InvalidFormat .

extension 是关联格式 (没有 .) 的文件扩展名。

readFunc and writeFunc 参数是指向读写一组键/值对的函数指针。 QIODevice 的读写函数参数始终以二进制方式被打开 (即,没有 QIODevice::Text 标志)。

caseSensitivity 参数指定键是否区分大小写。这会有所不同,当查找值使用 QSettings 。默认是区分大小写的。

默认情况下,若使用就组织名称和应用程序名称而言工作的某一构造函数,则所用文件系统位置如同 IniFormat 。使用 setPath () 去指定其它位置。

范例:

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");
    ...
}
					

注意: 此函数是 thread-safe .

该函数在 Qt 4.1 引入。

另请参阅 setPath ().

void QSettings:: remove (const QString & key )

移除设置 key 和任何子设置为 key .

范例:

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"]
					

注意,若某一回退位置包含具有相同键的设置,在调用 remove() 后该设置将可见。

key 为空字符串,所有键在当前 group () 被移除。例如:

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"]
					

注意:Windows 注册表和 INI 文件使用不区分大小写的键,而 macOS 和 iOS 的 CFPreferences API 使用区分大小写的键。要避免可移植性问题,见 区间和键句法 规则。

另请参阅 setValue (), value (),和 contains ().

作用域 QSettings:: scope () const

返回用于存储设置的作用域。

该函数在 Qt 4.4 引入。

另请参阅 format (), organizationName (),和 applicationName ().

void QSettings:: setArrayIndex ( int i )

将当前数组索引设为 i 。调用函数,譬如 setValue (), value (), remove (),和 contains () 将操作该索引数组条目。

必须调用 beginReadArray () 或 beginWriteArray () 在可以调用此函数之前。

[static] void QSettings:: setDefaultFormat ( Format format )

将默认文件格式设为给定 format ,用于存储设置为 QSettings ( QObject *) 构造函数。

若未设置默认格式, QSettings::NativeFormat 被使用。见文档编制了解 QSettings 构造函数,查看构造函数是否会忽略此函数。

该函数在 Qt 4.4 引入。

另请参阅 defaultFormat () 和 format ().

void QSettings:: setFallbacksEnabled ( bool b )

把是否启用回退设为 b .

默认情况下,回退是启用的。

另请参阅 fallbacksEnabled ().

void QSettings:: setIniCodec ( QTextCodec * codec )

设置访问 INI 文件的编解码器 (包括 .conf 文件在 Unix) 到 codec 。编解码器被用于解码从 INI 文件读取的任何数据,和对写入文件的任何数据进行编码。默认情况下,不使用编解码器,和使用标准 INI 转义序列编码非 ASCII 字符。

警告: 之后必须立即设置编解码器当创建 QSettings 对象,在访问任何数据之前。

该函数在 Qt 4.5 引入。

另请参阅 iniCodec ().

void QSettings:: setIniCodec (const char * codecName )

这是重载函数。

设置访问 INI 文件的编解码器 (包括 .conf 文件在 Unix) 到 QTextCodec 为指定编码通过 codecName 。常见值对于 codecName 包括 ISO 8859-1、UTF-8 及 UTF-16。若编码无法识别,则什么都不发生。

该函数在 Qt 4.5 引入。

另请参阅 QTextCodec::codecForName ().

[static] void QSettings:: setPath ( Format format , 作用域 scope , const QString & path )

设置用于存储设置的路径为给定 format and scope ,到 path format 可以是自定义格式。

下表汇总了默认值:

平台 格式 作用域 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 和 iOS IniFormat UserScope $HOME/.config
SystemScope /etc/xdg

默认 UserScope 路径在 Unix、macOS 及 iOS ( $HOME/.config 或 $HOME/Settings) 可以由用户覆盖通过设置 XDG_CONFIG_HOME 环境变量。默认 SystemScope 路径在 Unix、macOS 及 iOS ( /etc/xdg ) 可以被覆盖当构建 Qt 库使用 configure 脚本的 -sysconfdir 标志 (见 QLibraryInfo 了解细节)。

设置 NativeFormat 路径在 Windows、macOS 及 iOS,无效。

警告: 此函数不影响现有 QSettings 对象。

该函数在 Qt 4.1 引入。

另请参阅 registerFormat ().

void QSettings:: setValue (const QString & key , const QVariant & value )

设置值为设置 key to value 。若 key 已存在,先前值被覆写。

注意:Windows 注册表和 INI 文件使用不区分大小写的键,而 macOS 和 iOS 的 CFPreferences API 使用区分大小写的键。要避免可移植性问题,见 区间和键句法 规则。

范例:

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 (),和 contains ().

Status QSettings:: status () const

返回状态码指示遇到的首个错误通过 QSettings ,或 QSettings::NoError 若没有出现错误。

注意, QSettings 延迟履行某些操作。出于此原因,可能想要调用 sync () 以确保数据存储在 QSettings 被写入磁盘在调用 status() 之前。

另请参阅 sync ().

void QSettings:: sync ()

把任何未保存改变写入永久存储,并重新加载同时已被其它应用程序改变的任何设置。

此函数被自动调用从 QSettings 的析构函数和通过定期间隔的事件循环,因此,通常不需要自己调用它。

另请参阅 status ().

QVariant QSettings:: value (const QString & key , const QVariant & defaultValue = QVariant()) const

返回值为设置 key 。若设置不存在,返回 defaultValue .

若未指定默认值,默认 QVariant 被返回。

注意:Windows 注册表和 INI 文件使用不区分大小写的键,而 macOS 和 iOS 的 CFPreferences API 使用区分大小写的键。要避免可移植性问题,见 区间和键句法 规则。

范例:

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
					

另请参阅 setValue (), contains (),和 remove ().