QSettings¶
Synopsis¶
Functions¶
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]])
Static functions¶
def
defaultFormat
()def
setDefaultFormat
(format)def
setPath
(format, scope, path)
Detailed Description¶
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on macOS and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.
QSettings
is 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
, allowing you to save most value-based types, such asQString
,QRect
, andQImage
, with the minimum of effort.If all you need is a non-persistent memory-based structure, consider using
QMap
<QString
,QVariant
> instead.
Basic Usage¶
When creating a
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 theQSettings
object as follows:QSettings settings("MySoft", "Star Runner");
QSettings
objects can be created either on the stack or on the heap (i.e. usingnew
). Constructing and destroying aQSettings
object is very fast.If you use
QSettings
from many places in your application, you might want to specify the organization name and the application name usingsetOrganizationName()
andsetApplicationName()
, and then use the defaultQSettings
constructor: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 Notes
below for details.)
QSettings
stores settings. Each setting consists of aQString
that specifies the setting’s name (the key ) and aQVariant
that stores the data associated with the key. To write a setting, usesetValue()
. For example:settings.setValue("editor/wrapMargin", 68);If there already exists a setting with the same key, the existing value is overwritten by the new value. For efficiency, the changes may not be saved to permanent storage immediately. (You can always call
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 nullQVariant
(which can be converted to the integer 0). You can specify another default value by passing a second argument tovalue()
:int margin = settings.value("editor/wrapMargin", 80).toInt();To test whether a given key exists, call
contains()
. To remove the setting associated with a key, callremove()
. To obtain the list of all keys, callallKeys()
. To remove all keys, callclear()
.
QVariant and GUI Types¶
Because
QVariant
is part of the Qt Core module, it cannot provide conversion functions to data types such asQColor
,QImage
, andQPixmap
, which are part of Qt GUI. In other words, there is notoColor()
,toImage()
, ortoPixmap()
functions inQVariant
.Instead, you can use the
value()
template function. For example:settings = QSettings("MySoft", "Star Runner") color = QColor(settings.value("DataPump/bgcolor"))The inverse conversion (e.g., from
QColor
toQVariant
) is automatic for all data types supported byQVariant
, including GUI-related types:settings = QSettings("MySoft", "Star Runner") color = palette().background().color() settings.setValue("DataPump/bgcolor", color)Custom types registered using
qRegisterMetaType()
andqRegisterMetaTypeStreamOperators()
can be stored usingQSettings
.
Section and Key Syntax¶
Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, follow these simple rules:
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
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());If you want to save or restore many settings with the same prefix, you can specify the prefix using
beginGroup()
and callendGroup()
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();If a group is set using
beginGroup()
, the behavior of most functions changes consequently. Groups can be set recursively.In addition to groups,
QSettings
also supports an “array” concept. SeebeginReadArray()
andbeginWriteArray()
for details.
Fallback Mechanism¶
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:
a user-specific location for the Star Runner application
a user-specific location for all applications by MySoft
a system-wide location for the Star Runner application
a system-wide location for all applications by MySoft
(See
Platform-Specific Notes
below for information on what these locations are on the different platforms supported by Qt.)If a key cannot be found in the first location, the search goes on in the second location, and so on. This enables you to store system-wide or organization-wide settings and to override them on a per-user or per-application basis. To turn off this mechanism, call
setFallbacksEnabled
(false).Although keys from all four locations are available for reading, only the first file (the user-specific location for the application at hand) is accessible for writing. To write to any of the other files, omit the application name and/or specify
SystemScope
(as opposed toUserScope
, the default).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 theQSettings
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
User, Application
X
User, Organization
o
X
System, Application
o
X
System, Organization
o
o
o
X
The beauty of this mechanism is that it works on all platforms supported by Qt and that it still gives you a lot of flexibility, without requiring you to specify any file names or registry paths.
If you want to use INI files on all platforms instead of the native API, you can pass
IniFormat
as the first argument to theQSettings
constructor, followed by the scope, the organization name, and the application name:QSettings settings(QSettings::IniFormat, QSettings::UserScope, "MySoft", "Star Runner");Note that INI files lose the distinction between numeric data and the strings used to encode them, so values written as numbers shall be read back as
QString
. The numeric value can be recovered usingtoInt()
,toDouble()
and related functions.The Settings Editor example lets you experiment with different settings location and with fallbacks turned on or off.
Restoring the State of a GUI Application¶
QSettings
is often used to store the state of a GUI application. The following example illustrates how to useQSettings
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(); }See Window Geometry for a discussion on why it is better to call
resize()
andmove()
rather thansetGeometry()
to restore a window’s geometry.The
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(); } }See the Application example for a self-contained example that uses
QSettings
.
Accessing Settings from Multiple Threads or Processes Simultaneously¶
QSettings
is reentrant. This means that you can use distinctQSettings
object in different threads simultaneously. This guarantee stands even when theQSettings
objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through oneQSettings
object, the change will immediately be visible in any otherQSettings
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. ForIniFormat
, it uses advisory file locking and a smart merging algorithm to ensure data integrity. The condition for that to work is that the writeable configuration file must be a regular file and must reside in a directory that the current user can create new, temporary files in. If that is not the case, then one must usesetAtomicSyncRequired()
to turn the safety off.Note that
sync()
imports changes made by other processes (in addition to writing the changes from thisQSettings
).
Platform-Specific Notes¶
Locations Where Application Settings Are Stored¶
As mentioned in the
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.On Unix systems, if the file format is
NativeFormat
, the following files are used by default:
$HOME/.config/MySoft/Star Runner.conf
(Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.conf
)
$HOME/.config/MySoft.conf
(Qt for Embedded Linux:$HOME/Settings/MySoft.conf
)for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.conf
for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft.conf
Note
If XDG_CONFIG_DIRS is unset, the default value of
/etc/xdg
is used.On macOS and iOS, if the file format is
NativeFormat
, these files are used by default:
$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
On Windows,
NativeFormat
settings are stored in the following registry paths:
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
Note
On Windows, for 32-bit programs running in WOW64 mode, settings are stored in the following registry path:
HKEY_LOCAL_MACHINE\Software\WOW6432node
.If the file format is
NativeFormat
, this is “Settings/MySoft/Star Runner.conf” in the application’s home directory.If the file format is
IniFormat
, the following files are used on Unix, macOS, and iOS:
$HOME/.config/MySoft/Star Runner.ini
(Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.ini
)
$HOME/.config/MySoft.ini
(Qt for Embedded Linux:$HOME/Settings/MySoft.ini
)for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft/Star Runner.ini
for each directory <dir> in $XDG_CONFIG_DIRS:
<dir>/MySoft.ini
Note
If XDG_CONFIG_DIRS is unset, the default value of
/etc/xdg
is used.On Windows, the following files are used:
FOLDERID_RoamingAppData\MySoft\Star Runner.ini
FOLDERID_RoamingAppData\MySoft.ini
FOLDERID_ProgramData\MySoft\Star Runner.ini
FOLDERID_ProgramData\MySoft.ini
The identifiers prefixed by
FOLDERID_
are special item ID lists to be passed to the Win32 API functionSHGetKnownFolderPath()
to obtain the corresponding path.
FOLDERID_RoamingAppData
usually points toC:\Users\*User Name*\AppData\Roaming
, also shown by the environment variable%APPDATA%
.
FOLDERID_ProgramData
usually points toC:\ProgramData
.If the file format is
IniFormat
, this is “Settings/MySoft/Star Runner.ini” in the application’s home directory.The paths for the
.ini
and.conf
files can be changed usingsetPath()
. On Unix, macOS, and iOS the user can override them by setting theXDG_CONFIG_HOME
environment variable; seesetPath()
for details.
Accessing INI and .plist Files Directly¶
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 passIniFormat
as second argument. For example:settings = QSettings("/home/petra/misc/myapp.ini", QSettings.IniFormat)You can then use the
QSettings
object to read and write settings in the file.On macOS and iOS, you can access property list
.plist
files by passingNativeFormat
as second argument. For example:settings = QSettings("/Users/petra/misc/myapp.plist", QSettings.NativeFormat)
Accessing the Windows Registry Directly¶
On Windows,
QSettings
lets 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 aQSettings
object with a path in the registry andNativeFormat
.For example:
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.
Accessing Common Registry Settings on 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.
Platform Limitations¶
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
instead of theNativeFormat
.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 typeREG_EXPAND_SZ
will change toREG_SZ
.On macOS and 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) will hide these global settings.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, callsetOrganizationDomain()
,setOrganizationName()
, andsetApplicationName()
in yourmain()
function and then use the defaultQSettings
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")On macOS, permissions to access settings not belonging to the current user (i.e.
SystemScope
) have changed with 10.7 (Lion). Prior to that version, users having admin rights could access these. For 10.7 and 10.8 (Mountain Lion), only root can. However, 10.9 (Mavericks) changes that rule again but only for the native format (plist files).See also
QVariant
QSessionManager
Settings Editor Example Application Example
- class PySide2.QtCore.QSettings([parent=None])¶
PySide2.QtCore.QSettings(format, scope, organization[, application=””[, parent=None]])
PySide2.QtCore.QSettings(scope[, parent=None])
PySide2.QtCore.QSettings(scope, organization[, application=””[, parent=None]])
PySide2.QtCore.QSettings(fileName, format[, parent=None])
PySide2.QtCore.QSettings(organization[, application=””[, parent=None]])
- param parent:
- param organization:
str
- param application:
str
- param format:
- param fileName:
str
- param scope:
Constructs a
QSettings
object for accessing settings of the application and organization set previously with a call tosetOrganizationName()
,setOrganizationDomain()
, andsetApplicationName()
.The scope is
UserScope
and the format isdefaultFormat()
(NativeFormat
by default). UsesetDefaultFormat()
before calling this constructor to change the default format used by this constructor.The code
settings = QSettings("Moose Soft", "Facturo-Pro")
is equivalent to
QCoreApplication.setOrganizationName("Moose Soft") QCoreApplication.setApplicationName("Facturo-Pro") settings = QSettings()
If
setOrganizationName()
andsetApplicationName()
has not been previously called, theQSettings
object will not be able to read or write any settings, andstatus()
will returnAccessError
.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.
Constructs a
QSettings
object for accessing settings of the application calledapplication
from the organization calledorganization
, and with parentparent
.If
scope
isUserScope
, theQSettings
object searches user-specific settings first, before it searches system-wide settings as a fallback. Ifscope
isSystemScope
, theQSettings
object ignores user-specific settings and provides access to system-wide settings.If
format
isNativeFormat
, the native API is used for storing settings. Ifformat
isIniFormat
, the INI format is used.If no application name is given, the
QSettings
object will only access the organization-widelocations
.Constructs a
QSettings
object in the same way asQSettings
(QObject
*parent) but with the givenscope
.See also
QSettings(QObject *parent)
Constructs a
QSettings
object for accessing settings of the application calledapplication
from the organization calledorganization
, and with parentparent
.If
scope
isUserScope
, theQSettings
object searches user-specific settings first, before it searches system-wide settings as a fallback. Ifscope
isSystemScope
, theQSettings
object ignores user-specific settings and provides access to system-wide settings.The storage format is set to
NativeFormat
(i.e. callingsetDefaultFormat()
before calling this constructor has no effect).If no application name is given, the
QSettings
object will only access the organization-widelocations
.See also
- PySide2.QtCore.QSettings.Status¶
The following status values are possible:
Constant
Description
QSettings.NoError
No error occurred.
QSettings.AccessError
An access error occurred (e.g. trying to write to a read-only file).
QSettings.FormatError
A format error occurred (e.g. loading a malformed INI file).
See also
- PySide2.QtCore.QSettings.Format¶
This enum type specifies the storage format used by
QSettings
.Constant
Description
QSettings.NativeFormat
Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry; on macOS and iOS, this means the CFPreferences API; on Unix, this means textual configuration files in INI format.
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
Store the settings in INI files. Note that INI files lose the distinction between numeric data and the strings used to encode them, so values written as numbers shall be read back as
QString
.QSettings.InvalidFormat
Special value returned by
registerFormat()
.On Unix, and mean the same thing, except that the file extension is different (
.conf
for ,.ini
for ).The INI file format is a Windows file format that Qt supports on all platforms. In the absence of an INI standard, we try to follow what Microsoft does, with the following exceptions:
If you store types that
QVariant
can’t convert toQString
(e.g.,QPoint
,QRect
, andQSize
), Qt uses an@
-based syntax to encode the type. For example:pos = @Point(100 100)
To minimize compatibility issues, any
@
that doesn’t appear at the first position in the value or that isn’t followed by a Qt type (Point
,Rect
,Size
, etc.) is treated as a normal character.Although backslash is a special character in INI files, most Windows applications don’t escape backslashes (
\
) in file paths:windir = C:\Windows
QSettings
always treats backslash as a special character and provides no API for reading or writing such entries.The INI file format has severe restrictions on the syntax of a key. Qt works around this by using
%
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.Following the philosophy that we should be liberal in what we accept and conservative in what we generate,
QSettings
will accept Latin-1 encoded INI files, but generate pure ASCII files, where non-ASCII values are encoded using standard INI escape sequences. To make the INI files more readable (but potentially less compatible), callsetIniCodec()
.
See also
registerFormat()
setPath()
- PySide2.QtCore.QSettings.Scope¶
This enum specifies whether settings are user-specific or shared by all users of the same system.
Constant
Description
QSettings.UserScope
Store settings in a location specific to the current user (e.g., in the user’s home directory).
QSettings.SystemScope
Store settings in a global location, so that all users on the same machine access the same set of settings.
See also
- PySide2.QtCore.QSettings.allKeys()¶
- Return type:
list of strings
Returns a list of all keys, including subkeys, that can be read using the
QSettings
object.Example:
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"]
If a group is set using
beginGroup()
, only the keys in the group are returned, without the group prefix:settings.beginGroup("fridge") keys = settings.allKeys() # keys: ["color", "size"]
See also
- PySide2.QtCore.QSettings.applicationName()¶
- Return type:
str
Returns the application name used for storing the settings.
- PySide2.QtCore.QSettings.beginGroup(prefix)¶
- Parameters:
prefix – str
Appends
prefix
to the current group.The current group is automatically prepended to all keys specified to
QSettings
. In addition, query functions such aschildGroups()
,childKeys()
, andallKeys()
are based on the group. By default, no group is set.Groups are useful to avoid typing in the same setting paths over and over. For example:
settings.beginGroup("mainwindow") settings.setValue("size", win.size()) settings.setValue("fullScreen", win.isFullScreen()) settings.endGroup() settings.beginGroup("outputpanel") settings.setValue("visible", panel.isVisible()) settings.endGroup()
This will set the value of three settings:
mainwindow/size
mainwindow/fullScreen
outputpanel/visible
Call
endGroup()
to reset the current group to what it was before the corresponding call. Groups can be nested.See also
- PySide2.QtCore.QSettings.beginReadArray(prefix)¶
- Parameters:
prefix – str
- Return type:
int
Adds
prefix
to the current group and starts reading from an array. Returns the size of the array.Example:
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()
Use
beginWriteArray()
to write the array in the first place.See also
- PySide2.QtCore.QSettings.beginWriteArray(prefix[, size=-1])¶
- Parameters:
prefix – str
size – int
Adds
prefix
to the current group and starts writing an array of sizesize
. Ifsize
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()
.See also
- PySide2.QtCore.QSettings.childGroups()¶
- Return type:
list of strings
Returns a list of all key top-level groups that contain keys that can be read using the
QSettings
object.Example:
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"]
If a group is set using
beginGroup()
, the first-level keys in that group are returned, without the group prefix.settings.beginGroup("fridge") groups = settings.childGroups() # groups: []
You can navigate through the entire setting hierarchy using
childKeys()
and recursively.See also
- PySide2.QtCore.QSettings.childKeys()¶
- Return type:
list of strings
Returns a list of all top-level keys that can be read using the
QSettings
object.Example:
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"]
If a group is set using
beginGroup()
, the top-level keys in that group are returned, without the group prefix:settings.beginGroup("fridge") keys = settings.childKeys() # keys: ["color", "size"]
You can navigate through the entire setting hierarchy using and
childGroups()
recursively.See also
- PySide2.QtCore.QSettings.clear()¶
Removes all entries in the primary location associated to this
QSettings
object.Entries in fallback locations are not removed.
If you only want to remove the entries in the current
group()
, use remove(“”) instead.See also
- PySide2.QtCore.QSettings.contains(key)¶
- Parameters:
key – str
- Return type:
bool
Returns
true
if there exists a setting calledkey
; returns false otherwise.If a group is set using
beginGroup()
,key
is taken to be relative to that group.Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the
Section and Key Syntax
rules.See also
- static PySide2.QtCore.QSettings.defaultFormat()¶
- Return type:
Returns default file format used for storing settings for the
QSettings
(QObject
*) constructor. If no default format is set,NativeFormat
is used.See also
- PySide2.QtCore.QSettings.endArray()¶
Closes the array that was started using
beginReadArray()
orbeginWriteArray()
.See also
- PySide2.QtCore.QSettings.endGroup()¶
Resets the group to what it was before the corresponding
beginGroup()
call.Example:
settings.beginGroup("alpha") # settings.group() == "alpha" settings.beginGroup("beta") # settings.group() == "alpha/beta" settings.endGroup() # settings.group() == "alpha" settings.endGroup() # settings.group() == ""
See also
- PySide2.QtCore.QSettings.fallbacksEnabled()¶
- Return type:
bool
Returns
true
if fallbacks are enabled; returnsfalse
otherwise.By default, fallbacks are enabled.
See also
- PySide2.QtCore.QSettings.fileName()¶
- Return type:
str
Returns the path where settings written using this
QSettings
object are stored.On Windows, if the format is
NativeFormat
, the return value is a system registry path, not a file path.See also
- PySide2.QtCore.QSettings.format()¶
- Return type:
Returns the format used for storing the settings.
- PySide2.QtCore.QSettings.group()¶
- Return type:
str
Returns the current group.
See also
- PySide2.QtCore.QSettings.iniCodec()¶
- Return type:
Returns the codec that is used for accessing INI files. By default, no codec is used, so
None
is returned.See also
- PySide2.QtCore.QSettings.isAtomicSyncRequired()¶
- Return type:
bool
Returns
true
ifQSettings
is only allowed to perform atomic saving and reloading (synchronization) of the settings. Returnsfalse
if it is allowed to save the settings contents directly to the configuration file.The default is
true
.See also
- PySide2.QtCore.QSettings.isWritable()¶
- Return type:
bool
Returns
true
if settings can be written using thisQSettings
object; returnsfalse
otherwise.One reason why might return false is if
QSettings
operates on a read-only file.Warning
This function is not perfectly reliable, because the file permissions can change at any time.
See also
- PySide2.QtCore.QSettings.organizationName()¶
- Return type:
str
Returns the organization name used for storing the settings.
- PySide2.QtCore.QSettings.remove(key)¶
- Parameters:
key – str
Removes the setting
key
and any sub-settings ofkey
.Example:
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 .
If
key
is an empty string, all keys in the currentgroup()
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"]
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the
Section and Key Syntax
rules.See also
- PySide2.QtCore.QSettings.scope()¶
- Return type:
Returns the scope used for storing the settings.
See also
- PySide2.QtCore.QSettings.setArrayIndex(i)¶
- Parameters:
i – int
Sets the current array index to
i
. Calls to functions such assetValue()
,value()
,remove()
, andcontains()
will operate on the array entry at that index.You must call
beginReadArray()
orbeginWriteArray()
before you can call this function.
- PySide2.QtCore.QSettings.setAtomicSyncRequired(enable)¶
- Parameters:
enable – bool
Configures whether
QSettings
is required to perform atomic saving and reloading (synchronization) of the settings. If theenable
argument istrue
(the default),sync()
will only perform synchronization operations that are atomic. If this is not possible,sync()
will fail andstatus()
will be an error condition.Setting this property to
false
will allowQSettings
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 aIniFormat
configuration file that exists in an otherwise non-writeable directory or NTFS Alternate Data Streams.See
QSaveFile
for more information on the feature.See also
- static PySide2.QtCore.QSettings.setDefaultFormat(format)¶
- Parameters:
format –
Format
Sets the default file format to the given
format
, which is used for storing settings for theQSettings
(QObject
*) constructor.If no default format is set,
NativeFormat
is used. See the documentation for theQSettings
constructor you are using to see if that constructor will ignore this function.See also
- PySide2.QtCore.QSettings.setFallbacksEnabled(b)¶
- Parameters:
b – bool
Sets whether fallbacks are enabled to
b
.By default, fallbacks are enabled.
See also
- PySide2.QtCore.QSettings.setIniCodec(codec)¶
- Parameters:
codec –
PySide2.QtCore.QTextCodec
Sets the codec for accessing INI files (including
.conf
files on Unix) tocodec
. The codec is used for decoding any data that is read from the INI file, and for encoding any data that is written to the file. By default, no codec is used, and non-ASCII characters are encoded using standard INI escape sequences.Warning
The codec must be set immediately after creating the
QSettings
object, before accessing any data.See also
- PySide2.QtCore.QSettings.setIniCodec(codecName)
- Parameters:
codecName – str
This is an overloaded function.
Sets the codec for accessing INI files (including
.conf
files on Unix) to theQTextCodec
for the encoding specified bycodecName
. Common values forcodecName
include “ISO 8859-1”, “UTF-8”, and “UTF-16”. If the encoding isn’t recognized, nothing happens.See also
- static PySide2.QtCore.QSettings.setPath(format, scope, path)¶
-
Sets the path used for storing settings for the given
format
andscope
, topath
. Theformat
can be a custom format.The table below summarizes the default values:
Platform
Format
Scope
Path
Windows
IniFormat
UserScope
FOLDERID_RoamingAppData
SystemScope
FOLDERID_ProgramData
Unix
NativeFormat
,IniFormat
UserScope
$HOME/.config
SystemScope
/etc/xdg
Qt for Embedded Linux
NativeFormat
,IniFormat
UserScope
$HOME/Settings
SystemScope
/etc/xdg
macOS and iOS
IniFormat
UserScope
$HOME/.config
SystemScope
/etc/xdg
The default
UserScope
paths on Unix, macOS, and iOS ($HOME/.config
or $HOME/Settings) can be overridden by the user by setting theXDG_CONFIG_HOME
environment variable. The defaultSystemScope
paths on Unix, macOS, and iOS (/etc/xdg
) can be overridden when building the Qt library using theconfigure
script’s-sysconfdir
flag (seeQLibraryInfo
for details).Setting the
NativeFormat
paths on Windows, macOS, and iOS has no effect.Warning
This function doesn’t affect existing
QSettings
objects.See also
registerFormat()
- PySide2.QtCore.QSettings.setValue(key, value)¶
- Parameters:
key – str
value – object
Sets the value of setting
key
tovalue
. If thekey
already exists, the previous value is overwritten.Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the
Section and Key Syntax
rules.Example:
settings = QSettings() settings.setValue("interval", 30) settings.value("interval") # returns 30 settings.setValue("interval", 6.55) settings.value("interval") # returns 6.55
See also
- PySide2.QtCore.QSettings.status()¶
- Return type:
Returns a status code indicating the first error that was met by
QSettings
, orNoError
if no error occurred.Be aware that
QSettings
delays performing some operations. For this reason, you might want to callsync()
to ensure that the data stored inQSettings
is written to disk before calling .See also
- PySide2.QtCore.QSettings.sync()¶
Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application.
This function is called automatically from
QSettings
‘s destructor and by the event loop at regular intervals, so you normally don’t need to call it yourself.See also
- PySide2.QtCore.QSettings.value(arg__1[, defaultValue=0[, type=0]])¶
- Parameters:
arg__1 – str
defaultValue – object
type – object
- Return type:
object
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.