QSettings

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

Inheritance diagram of PySide2.QtCore.QSettings

概要

函数

静态函数

详细描述

用户通常期望应用程序跨会话记住其设置 (窗口大小和位置、选项、等等)。此信息常存储在 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 custom storage formats .

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 setOrganizationName() and setApplicationName() , and then use the default QSettings 构造函数:

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

(Here, we also specify the organization’s Internet domain. When the Internet domain is set, it is used on macOS and iOS instead of the organization name, since macOS and iOS applications conventionally use Internet domains to identify themselves. If no domain is set, a fake domain is derived from the organization name. See the Platform-Specific 注意事项 了解细节。)

QSettings stores settings. Each setting consists of a QString that specifies the setting’s name (the key ) 和 QVariant 存储键关联数据。要写入设置,使用 setValue() 。例如:

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

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

You can get a setting’s value back using 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() . To remove the setting associated with a key, call remove() . To obtain the list of all keys, call allKeys() . To remove all keys, call clear() .

QVariant 和 GUI 类型

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

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

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

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

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

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

区间和键句法

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

  1. Always refer to the same key using the same case. For example, if you refer to a key as “text fonts” in one place in your code, don’t refer to it as “Text Fonts” somewhere else.

  2. Avoid key names that are identical except for the case. For example, if you have a key called “MainWindow”, don’t try to save another key as “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.

You can form hierarchical keys using the ‘/’ character as a separator, similar to Unix file paths. For example:

settings.setValue("mainwindow/size", win->size());
settings.setValue("mainwindow/fullScreen", win->isFullScreen());
settings.setValue("outputpanel/visible", panel->isVisible());
												

若希望保存 (或还原) 许多采用相同前缀的设置,可以指定前缀使用 beginGroup() 和调用 endGroup() at the end. Here’s the same example again, but this time using the group mechanism:

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() , the behavior of most functions changes consequently. Groups can be set recursively.

In addition to groups, QSettings also supports an “array” concept. See beginReadArray() and 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 为所有应用程序的系统范围位置

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

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

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

Let’s see with an example:

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.

Locations

obj1

obj2

obj3

obj4

  1. User, Application

X

  1. User, Organization

o

X

  1. System, Application

o

X

  1. System, Organization

o

o

o

X

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

若希望在所有平台使用 INI 文件而不是本机 API,可以传递 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");
												

注意:不预留类型信息,当从 INI 文件读取设置时;所有值将返回作为 QString .

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

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

窗口几何体 了解为什么更好的论述,调用 resize() and move() 而不是 setGeometry() to restore a window’s geometry.

readSettings() and writeSettings() functions must be called from the main window’s constructor and close event handler as follows:

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 reentrant. 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, provided certain conditions are met. For IniFormat ,它使用咨询文件锁定和智能合并算法,以确保数据的完整性。工作条件是可写配置文件必须为常规文件,且必须位于当前用户可以在其中创建新临时文件的目录下。若不是这种情况,就必须使用 setAtomicSyncRequired() to turn the safety off.

注意: sync() imports changes made by other processes (in addition to writing the changes from this QSettings ).

特定平台注意事项

存储应用程序设置的位置

作为提及在 Fallback Mechanism 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 , this is “Settings/MySoft/Star Runner.conf” in the application’s home directory.

若文件格式为 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 , this is “Settings/MySoft/Star Runner.ini” in the application’s home directory.

路径对于 .ini and .conf 文件可以改变使用 setPath() . On Unix, macOS, and iOS the user can override them by setting the 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 IniFormat 作为第 2 自变量。例如:

settings = QSettings("/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 文件通过传递 NativeFormat 作为第 2 自变量。例如:

settings = QSettings("/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 NativeFormat .

例如:

settings = QSettings("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 公共注册表设置

On Windows, it is possible for a key to have both a value and subkeys. Its default value is accessed by using “Default” or “.” in place of a subkey:

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"
												

On other platforms than Windows, “Default” and “.” would be treated as regular subkeys.

平台的局限性

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:

  • The Windows system registry has the following limitations: A subkey may not exceed 255 characters, an entry’s value may not exceed 16,383 characters, and all the values of a key may not exceed 65,535 characters. One way to work around these limitations is to store the settings using the 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() will return some extra keys for global settings that apply to all applications. These keys can be read using value() but cannot be changed, only shadowed. Calling 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 setOrganizationDomain() , setOrganizationName() ,和 setApplicationName() 在您的 main() function and then use the default QSettings constructor. Another solution is to use preprocessor directives, for example:

    organizationName = "grenoullelogique.fr" if sys.platform.startswith('darwin') else "Grenoulle Logique"
    settings = QSettings(organizationName, "Squash")
    														
  • 在 macOS,访问不属于当前用户的设置的权限 (即 SystemScope ) 已于 10.7 (狮子) 版改变。在该版本之前,有 admin (管理员) 权限的用户可以访问这些。对于 10.7 和 10.8 (山狮) 版,只有 root 可以。然而,10.9 (小牛队) 版再次改变此规则,但只针对本机格式 (plist 文件)。

另请参阅

QVariant QSessionManager 设置编辑器范例 应用程序范例

class QSettings ( [ parent=None ] )

QSettings(format, scope, organization[, application=””[, parent=None]])

QSettings(scope[, parent=None])

QSettings(scope, organization[, application=””[, parent=None]])

QSettings(fileName, format[, parent=None])

QSettings(organization[, application=””[, parent=None]])

param parent

QObject

param organization

unicode

param application

unicode

param format

格式

param fileName

unicode

param scope

作用域

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

作用域是 UserScope 和格式为 defaultFormat() ( NativeFormat 默认情况下)。使用 setDefaultFormat() before calling this constructor to change the default format used by this constructor.

代码

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

相当于

QCoreApplication.setOrganizationName("Moose Soft")
QCoreApplication.setApplicationName("Facturo-Pro")
settings = QSettings()
												

setOrganizationName() and setApplicationName() has not been previously called, the QSettings object will not be able to read or write any settings, and status() will return AccessError .

You should supply both the domain (used by default on macOS and iOS) and the name (used by default elsewhere), although the code will cope if you supply only one, which will then be used (on all platforms), at odds with the usual naming of the file on platforms for which it isn’t the default.

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

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

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

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

构造 QSettings object in the same way as QSettings ( QObject *parent) 但采用给定 scope .

另请参阅

QSettings(QObject *parent)

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

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

存储格式被设为 NativeFormat (即:调用 setDefaultFormat() before calling this constructor has no effect).

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

PySide2.QtCore.QSettings. Status

下列状态值是可能的:

常量

描述

QSettings.NoError

没有发生错误。

QSettings.AccessError

发生访问错误 (如:试着写入只读文件)。

QSettings.FormatError

发生格式错误 (如:加载畸形 INI 文件)。

另请参阅

status()

PySide2.QtCore.QSettings. 格式

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

常量

描述

QSettings.NativeFormat

使用最适合平台的存储格式存储设置。在 Windows,这意味着系统注册表;在 macOS 和 iOS,这意味着 CFPreferences API;在 Unix,这意味着以 INI 格式正文配置文件。

QSettings.Registry32Format

Windows only: Explicitly access the 32-bit system registry from a 64-bit application running on 64-bit Windows. On 32-bit Windows or from a 32-bit application on 64-bit Windows, this works the same as specifying . This enum value was added in Qt 5.7.

QSettings.Registry64Format

Windows only: Explicitly access the 64-bit system registry from a 32-bit application running on 64-bit Windows. On 32-bit Windows or from a 64-bit application on 64-bit Windows, this works the same as specifying . This enum value was added in Qt 5.7.

QSettings.IniFormat

把设置存储在 INI 文件中。注意,不预留类型信息,当从 INI 文件读取设置时;所有值将被返回作为 QString .

QSettings.InvalidFormat

返回的特殊值由 registerFormat() .

On Unix, and mean the same thing, except that the file extension is different ( .conf for , .ini for ).

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

  • 若存储类型 QVariant can’t convert to QString (如, QPoint , QRect ,和 QSize ),Qt 使用 @ 基句法以编码类型。例如:

    pos = @Point(100 100)
    														

    为最小化兼容性问题,任何 @ that doesn’t appear at the first position in the value or that isn’t followed by a Qt type ( Point , Rect , Size ,等) 被视为正常字符。

  • Although backslash is a special character in INI files, most Windows applications don’t escape backslashes ( \ ) 在文件路径:

    windir = C:\Windows
    														

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

  • INI 文件格式对键句法有严格限定。Qt 要解决这是通过使用 % as an escape character in keys. In addition, if you save a top-level setting (a key with no slashes in it, e.g., “someKey”), it will appear in the INI file’s “General” section. To avoid overwriting other keys, if you save something using a key such as “General/someKey”, the key will be located in the “%General” section, not in the “General” section.

  • 遵循应该在接受的东西上是自由派,而在产生的东西上是保守派的哲学, QSettings 将接受 Latin-1 编码 INI 文件,但生成纯 ASCII 文件,使用标准 INI 转义序列编码其中的非 ASCII 值。要使 INI 文件更可读 (但潜在不太兼容),调用 setIniCodec() .

另请参阅

registerFormat() setPath()

PySide2.QtCore.QSettings. 作用域

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

常量

描述

QSettings.UserScope

Store settings in a location specific to the current user (e.g., in the user’s home directory).

QSettings.SystemScope

将设置存储在全局位置,以便同一计算机中的所有用户访问相同设置集。

另请参阅

setPath()

PySide2.QtCore.QSettings. allKeys ( )
返回类型

字符串列表

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

范例:

settings = QSettings()
settings.setValue("fridge/color", Qt.white)
settings.setValue("fridge/size", QSize(32, 96))
settings.setValue("sofa", True)
settings.setValue("tv", False)
keys = settings.allKeys();
# keys: ["fridge/color", "fridge/size", "sofa", "tv"]
												

若设置组使用 beginGroup() , only the keys in the group are returned, without the group prefix:

settings.beginGroup("fridge")
keys = settings.allKeys()
# keys: ["color", "size"]
												
PySide2.QtCore.QSettings. applicationName ( )
返回类型

unicode

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

PySide2.QtCore.QSettings. beginGroup ( prefix )
参数

prefix – unicode

追加 prefix 到当前组。

当前组自动前置所有指定键到 QSettings 。此外,查询函数譬如 childGroups() , childKeys() ,和 allKeys() are based on the group. By default, no group is set.

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

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() to reset the current group to what it was before the corresponding call. Groups can be nested.

PySide2.QtCore.QSettings. beginReadArray ( prefix )
参数

prefix – unicode

返回类型

int

添加 prefix to the current group and starts reading from an array. Returns the size of the array.

范例:

class Login:
    userName = ''
    password = ''
    logins = []
    ...
    settings = QSettings()
    size = settings.beginReadArray("logins")
    for i in range(size):
        settings.setArrayIndex(i)
        login = Login()
        login.userName = settings.value("userName")
        login.password = settings.value("password")
        logins.append(login)
    settings.endArray()
												

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

PySide2.QtCore.QSettings. beginWriteArray ( prefix [ , size=-1 ] )
参数
  • prefix – unicode

  • size int

添加 prefix to the current group and starts writing an array of size size 。若 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:

class Login:
    userName = ''
    password = ''
    logins = []
    ...
    settings = QSettings()
    settings.beginWriteArray("logins")
    for i in range(logins.size()):
        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() .

PySide2.QtCore.QSettings. childGroups ( )
返回类型

字符串列表

Returns a list of all key top-level groups that contain keys that can be read using the QSettings 对象。

范例:

settings = QSettings()
settings.setValue("fridge/color", Qt.white)
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", True)
settings.setValue("tv", False)
groups = settings.childGroups()
# group: ["fridge"]
												

若设置组使用 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 recursively.

PySide2.QtCore.QSettings. childKeys ( )
返回类型

字符串列表

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

范例:

settings = QSettings()
settings.setValue("fridge/color", Qt.white)
settings.setValue("fridge/size", QSize(32, 96))
settings.setValue("sofa", True)
settings.setValue("tv", False)
keys = settings.childKeys()
# keys: ["sofa", "tv"]
												

若设置组使用 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 and childGroups() recursively.

PySide2.QtCore.QSettings. clear ( )

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

不移除回退位置条目。

若只希望移除的条目在当前 group() , use remove(“”) instead.

PySide2.QtCore.QSettings. contains ( key )
参数

key – unicode

返回类型

bool

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

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

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

static PySide2.QtCore.QSettings. defaultFormat ( )
返回类型

格式

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

PySide2.QtCore.QSettings. endArray ( )

Closes the array that was started using beginReadArray() or beginWriteArray() .

PySide2.QtCore.QSettings. endGroup ( )

Resets the group to what it was before the corresponding beginGroup() 调用。

范例:

settings.beginGroup("alpha")
# settings.group() == "alpha"
settings.beginGroup("beta")
# settings.group() == "alpha/beta"
settings.endGroup()
# settings.group() == "alpha"
settings.endGroup()
# settings.group() == ""
												
PySide2.QtCore.QSettings. fallbacksEnabled ( )
返回类型

bool

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

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

PySide2.QtCore.QSettings. fileName ( )
返回类型

unicode

Returns the path where settings written using this QSettings object are stored.

在 Windows,若格式为 NativeFormat , the return value is a system registry path, not a file path.

PySide2.QtCore.QSettings. format ( )
返回类型

格式

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

PySide2.QtCore.QSettings. group ( )
返回类型

unicode

返回当前组。

PySide2.QtCore.QSettings. iniCodec ( )
返回类型

QTextCodec

返回用于访问 INI 文件的编解码器。默认情况下,不使用编解码器,因此 None 被返回。

另请参阅

setIniCodec()

PySide2.QtCore.QSettings. isAtomicSyncRequired ( )
返回类型

bool

返回 true if QSettings is only allowed to perform atomic saving and reloading (synchronization) of the settings. Returns false 若允许将设置内容直接保存到配置文件。

默认为 true .

PySide2.QtCore.QSettings. isWritable ( )
返回类型

bool

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

One reason why might return false is if QSettings 操作只读文件。

警告

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

PySide2.QtCore.QSettings. organizationName ( )
返回类型

unicode

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

PySide2.QtCore.QSettings. remove ( key )
参数

key – unicode

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

范例:

settings = QSettings()
settings.setValue("ape")
settings.setValue("monkey", 1)
settings.setValue("monkey/sea", 2)
settings.setValue("monkey/doe", 4)
settings.remove("monkey")
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 .

key 为空字符串,所有键在当前 group() are removed. For example:

settings = QSettings()
settings.setValue("ape")
settings.setValue("monkey", 1)
settings.setValue("monkey/sea", 2)
settings.setValue("monkey/doe", 4)
settings.beginGroup("monkey")
settings.remove("")
settings.endGroup()
keys = settings.allKeys()
# keys: ["ape"]
												

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

PySide2.QtCore.QSettings. scope ( )
返回类型

作用域

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

PySide2.QtCore.QSettings. setArrayIndex ( i )
参数

i int

将当前数组索引设为 i 。调用函数,譬如 setValue() , value() , remove() ,和 contains() will operate on the array entry at that index.

必须调用 beginReadArray() or beginWriteArray() before you can call this function.

PySide2.QtCore.QSettings. setAtomicSyncRequired ( enable )
参数

enable bool

配置是否 QSettings 要求履行设置的原子保存和重新加载 (同步)。若 enable 自变量为 true (默认), sync() will only perform synchronization operations that are atomic. If this is not possible, sync() will fail and status() will be an error condition.

把此特性设为 false 将允许 QSettings to write directly to the configuration file and ignore any errors trying to lock it against other processes trying to write at the same time. Because of the potential for corruption, this option should be used with care, but is required in certain conditions, like a IniFormat configuration file that exists in an otherwise non-writeable directory or NTFS Alternate Data Streams.

QSaveFile 了解有关特征的更多信息。

static PySide2.QtCore.QSettings. setDefaultFormat ( format )
参数

format 格式

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

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

PySide2.QtCore.QSettings. setFallbacksEnabled ( b )
参数

b bool

把是否启用回退设为 b .

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

PySide2.QtCore.QSettings. setIniCodec ( codec )
参数

codec QTextCodec

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

警告

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

另请参阅

iniCodec()

PySide2.QtCore.QSettings. setIniCodec ( codecName )
参数

codecName – str

这是重载函数。

设置访问 INI 文件的编解码器 (包括 .conf 文件在 Unix) 到 QTextCodec 为指定编码通过 codecName 。常见值对于 codecName include “ISO 8859-1”, “UTF-8”, and “UTF-16”. If the encoding isn’t recognized, nothing happens.

另请参阅

codecForName()

static PySide2.QtCore.QSettings. setPath ( format , scope , 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 script’s -sysconfdir 标志 (见 QLibraryInfo 了解细节)。

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

警告

This function doesn’t affect existing QSettings 对象。

另请参阅

registerFormat()

PySide2.QtCore.QSettings. setValue ( key , value )
参数
  • key – unicode

  • value – object

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

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

范例:

settings = QSettings()
settings.setValue("interval", 30)
settings.value("interval")      # returns 30
settings.setValue("interval", 6.55)
settings.value("interval")  # returns 6.55
												
PySide2.QtCore.QSettings. status ( )
返回类型

Status

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

注意: QSettings 延迟履行某些操作。出于此原因,可能想要调用 sync() to ensure that the data stored in QSettings is written to disk before calling .

另请参阅

sync()

PySide2.QtCore.QSettings. sync ( )

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

此函数被自动调用从 QSettings ‘s destructor and by the event loop at regular intervals, so you normally don’t need to call it yourself.

另请参阅

status()

PySide2.QtCore.QSettings. value ( arg__1 [ , defaultValue=0 [ , type=0 ] ] )
参数
  • arg__1 – unicode

  • defaultValue – object

  • type PyObject

返回类型

PyObject