def
allKeys
()
def
applicationName
()
def
beginGroup
(prefix)
def
beginReadArray
(prefix)
def
beginWriteArray
(prefix[, size=-1])
def
childGroups
()
def
childKeys
()
def
clear
()
def
contains
(key)
def
endArray
()
def
endGroup
()
def
fallbacksEnabled
()
def
fileName
()
def
format
()
def
group
()
def
iniCodec
()
def
isAtomicSyncRequired
()
def
isWritable
()
def
organizationName
()
def
remove
(key)
def
scope
()
def
setArrayIndex
(i)
def
setAtomicSyncRequired
(enable)
def
setFallbacksEnabled
(b)
def
setIniCodec
(codec)
def
setIniCodec
(codecName)
def
setValue
(key, value)
def
status
()
def
sync
()
def
value
(arg__1[, defaultValue=0[, type=0]])
def
defaultFormat
()
def
setDefaultFormat
(format)
def
setPath
(format, scope, path)
用户通常期望应用程序跨会话记住其设置 (窗口大小和位置、选项、等等)。此信息常存储在 Windows 的系统注册表中,macOS 和 iOS 的特性列表文件中。在缺乏标准的 Unix 系统,许多应用程序 (包括 KDE 应用程序) 使用 INI 文本文件。
QSettingsis an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supportscustom storage formats.
QSettings‘s API is based onQVariant,允许保存大多数基于值的类型,譬如QString,QRect,和QImage,采用最少努力。若需要的全是基于内存的非持久性结构,请考虑使用
QMap<QString,QVariant> 代替。
当创建
QSettingsobject, 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 theQSettingsobject as follows:QSettings settings("MySoft", "Star Runner");
QSettingsobjects can be created either on the stack or on the heap (i.e. usingnew). Constructing and destroying aQSettingsobject is very fast.若使用
QSettingsfrom many places in your application, you might want to specify the organization name and the application name usingsetOrganizationName()andsetApplicationName(), and then use the defaultQSettings构造函数: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 注意事项了解细节。)
QSettingsstores settings. Each setting consists of aQStringthat 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,
QSettingsreturns a nullQVariant(其可以被转换成整数 0)。可以指定另一默认值通过把第 2 自变量传递给value():int margin = settings.value("editor/wrapMargin", 80).toInt();要测试给定键是否存在,调用
contains(). To remove the setting associated with a key, callremove(). To obtain the list of all keys, callallKeys(). To remove all keys, callclear().
因为
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"))反向转换 (如,从
QColortoQVariant) 对于所有支持数据类型是自动通过QVariant,包括 GUI 相关类型:settings = QSettings("MySoft", "Star Runner") color = palette().background().color() settings.setValue("DataPump/bgcolor", color)自定义类型注册采用
qRegisterMetaType()andqRegisterMetaTypeStreamOperators()can be stored usingQSettings.
设置键可以包含任何 Unicode 字符。Windows 注册表和 INI 文件使用不区分大小写的键,而在 macOS 和 iOS 上的 CFPreferences API 使用区分大小写的键。为避免可移植性问题,遵循这些简单规则:
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.
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”.
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
QSettingsto ‘/’, 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,
QSettingsalso supports an “array” concept. SeebeginReadArray()andbeginWriteArray()了解细节。
Let’s assume that you have created a
QSettingsobject 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:
为 Star Runner 应用程序的特定用户位置
由 MySoft 为所有应用程序的特定用户位置
为 Star Runner 应用程序的系统范围位置
由 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
QSettingsobjects access which location. “ X ” means that the location is the main location associated to theQSettingsobject 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
User, Application
X
User, Organization
o
X
System, Application
o
X
System, Organization
o
o
o
X
这种机制的妙处是它工作于由 Qt 支持的所有平台,且仍然给予很大灵活性,不要求指定任何文件名 (或注册表路径)。
若希望在所有平台使用 INI 文件而不是本机 API,可以传递
IniFormatas the first argument to theQSettingsconstructor, followed by the scope, the organization name, and the application name:QSettings settings(QSettings::IniFormat, QSettings::UserScope, "MySoft", "Star Runner");注意:不预留类型信息,当从 INI 文件读取设置时;所有值将返回作为
QString.设置编辑器 范例允许您试验不同设置位置,及启用或禁用回退。
QSettingsis often used to store the state of a GUI application. The following example illustrates how to useQSettingsto 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()andmove()而不是setGeometry()to restore a window’s geometry.
readSettings()andwriteSettings()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.
QSettingsis reentrant. This means that you can use distinctQSettingsobject in different threads simultaneously. This guarantee stands even when theQSettingsobjects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through oneQSettingsobject, the change will immediately be visible in any otherQSettingsobjects that operate on the same location and that live in the same process.
QSettingscan 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. ForIniFormat,它使用咨询文件锁定和智能合并算法,以确保数据的完整性。工作条件是可写配置文件必须为常规文件,且必须位于当前用户可以在其中创建新临时文件的目录下。若不是这种情况,就必须使用setAtomicSyncRequired()to turn the safety off.注意:
sync()imports changes made by other processes (in addition to writing the changes from thisQSettings).
作为提及在
Fallback Mechanismsection,QSettingsstores 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,默认使用下列文件:
$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)对于每目录 <dir> 在 $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.conf对于每目录 <dir> 在 $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,对于运行在 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 使用下列文件:
$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)对于每目录 <dir> 在 $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.ini对于每目录 <dir> 在 $XDG_CONFIG_DIRS:
<dir>/MySoft.ini注意
若 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 函数的特殊项 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.路径对于
.iniand.conf文件可以改变使用setPath(). On Unix, macOS, and iOS the user can override them by setting theXDG_CONFIG_HOME环境变量;见setPath()了解细节。
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
QSettingsconstructor that takes a file name as first argument and passIniFormat作为第 2 自变量。例如:settings = QSettings("/home/petra/misc/myapp.ini", QSettings.IniFormat)You can then use the
QSettingsobject to read and write settings in the file.在 macOS 和 iOS,可以访问特性列表
.plist文件通过传递NativeFormat作为第 2 自变量。例如:settings = QSettings("/Users/petra/misc/myapp.plist", QSettings.NativeFormat)
在 Windows,
QSettingslets you access settings that have been written withQSettings(or settings in a supported format, e.g., string data) in the system registry. This is done by constructing aQSettingsobject with a path in the registry andNativeFormat.例如:
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
QSettingsobject 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
QSettingsto 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.
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
QSettingsattempts 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,
QSettingsdoes 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 typeREG_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 usingvalue()but cannot be changed, only shadowed. CallingsetFallbacksEnabled(false) 将隐藏这些全局设置。On macOS and iOS, the CFPreferences API used by
QSettingsexpects Internet domain names rather than organization names. To provide a uniform API,QSettingsderives 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, callsetOrganizationDomain(),setOrganizationName(),和setApplicationName()在您的main()function and then use the defaultQSettingsconstructor. 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 文件)。另请参阅
QVariantQSessionManager设置编辑器范例 应用程序范例
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
- 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 文件)。 |
另请参阅
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 文件读取设置时;所有值将被返回作为
|
|
QSettings.InvalidFormat |
返回的特殊值由
|
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 |
将设置存储在全局位置,以便同一计算机中的所有用户访问相同设置集。 |
另请参阅
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
句法
规则。
另请参阅
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.
group
(
)
¶
unicode
返回当前组。
另请参阅
PySide2.QtCore.QSettings.
iniCodec
(
)
¶
返回用于访问 INI 文件的编解码器。默认情况下,不使用编解码器,因此
None
被返回。
另请参阅
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.
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
了解有关特征的更多信息。
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
对象,在访问任何数据之前。
另请参阅
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.
另请参阅
PySide2.QtCore.QSettings.
setPath
(
format
,
scope
,
path
)
¶
设置用于存储设置的路径为给定
format
and
scope
,到
path
。
format
可以是自定义格式。
下表汇总了默认值:
|
平台 |
格式 |
作用域 |
Path |
|
Windows |
|
|
|
|
|
|
||
|
Unix |
|
|
|
|
|
|
||
|
Qt for Embedded Linux |
|
|
|
|
|
|
||
|
macOS 和 iOS |
|
|
|
|
|
|
默认
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
(
)
¶
返回状态代码指示遇到的首个错误通过
QSettings
,或
NoError
若没有发生错误。
注意:
QSettings
延迟履行某些操作。出于此原因,可能想要调用
sync()
to ensure that the data stored in
QSettings
is written to disk before calling .
另请参阅
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.
另请参阅
PySide2.QtCore.QSettings.
value
(
arg__1
[
,
defaultValue=0
[
,
type=0
]
]
)
¶
arg__1 – unicode
defaultValue – object
type
–
PyObject
PyObject