QSettings

Inheritance diagram of QSettings

Synopsis

Functions

Static functions

Detailed Description

The PySide.QtCore.QSettings class provides persistent platform-independent application settings.

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 XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.

PySide.QtCore.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 .

PySide.QtCore.QSettings ‘s API is based on PySide.QtCore.QVariant , allowing you to save most value-based types, such as PySide.QtCore.QString , PySide.QtCore.QRect , and PySide.QtGui.QImage , with the minimum of effort.

If all you need is a non-persistent memory-based structure, consider using QMap < PySide.QtCore.QString , PySide.QtCore.QVariant > instead.

Basic Usage

When creating a PySide.QtCore.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 PySide.QtCore.QSettings object as follows:

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

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

If you use PySide.QtCore.QSettings from many places in your application, you might want to specify the organization name and the application name using QCoreApplication.setOrganizationName() and QCoreApplication.setApplicationName() , and then use the default PySide.QtCore.QSettings constructor:

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

(Here, we also specify the organization’s Internet domain. When the Internet domain is set, it is used on Mac OS X instead of the organization name, since Mac OS X 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.)

PySide.QtCore.QSettings stores settings. Each setting consists of a PySide.QtCore.QString that specifies the setting’s name (the key ) and a PySide.QtCore.QVariant that stores the data associated with the key. To write a setting, use PySide.QtCore.QSettings.setValue() . 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 PySide.QtCore.QSettings.sync() to commit your changes.)

You can get a setting’s value back using PySide.QtCore.QSettings.value() :

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

If there is no setting with the specified name, PySide.QtCore.QSettings returns a null PySide.QtCore.QVariant (which can be converted to the integer 0). You can specify another default value by passing a second argument to PySide.QtCore.QSettings.value() :

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

To test whether a given key exists, call PySide.QtCore.QSettings.contains() . To remove the setting associated with a key, call PySide.QtCore.QSettings.remove() . To obtain the list of all keys, call PySide.QtCore.QSettings.allKeys() . To remove all keys, call PySide.QtCore.QSettings.clear() .

QVariant and GUI Types

Because PySide.QtCore.QVariant is part of the QtCore library, it cannot provide conversion functions to data types such as PySide.QtGui.QColor , PySide.QtGui.QImage , and PySide.QtGui.QPixmap , which are part of QtGui . In other words, there is no toColor() , toImage() , or toPixmap() functions in PySide.QtCore.QVariant .

Instead, you can use the QVariant.value() or the qVariantValue() template function. For example:

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

The inverse conversion (e.g., from PySide.QtGui.QColor to PySide.QtCore.QVariant ) is automatic for all data types supported by PySide.QtCore.QVariant , including GUI-related types:

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

Custom types registered using qRegisterMetaType() and qRegisterMetaTypeStreamOperators() can be stored using PySide.QtCore.QSettings .

Section and Key Syntax

Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, follow these simple rules:

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 PySide.QtCore.QSettings.beginGroup() and call PySide.QtCore.QSettings.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()

If a group is set using PySide.QtCore.QSettings.beginGroup() , the behavior of most functions changes consequently. Groups can be set recursively.

In addition to groups, PySide.QtCore.QSettings also supports an “array” concept. See PySide.QtCore.QSettings.beginReadArray() and PySide.QtCore.QSettings.beginWriteArray() for details.

Fallback Mechanism

Let’s assume that you have created a PySide.QtCore.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:

(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 QSettings.SystemScope (as opposed to QSettings.UserScope , the default).

Let’s see with an example:

obj1 = QSettings("MySoft", "Star Runner")
obj2 = QSettings("MySoft")
obj3 = QSettings(QSettings.SystemScope, "MySoft", "Star Runner")
obj4 = QSettings(QSettings.SystemScope, "MySoft")

The table below summarizes which PySide.QtCore.QSettings objects access which location. “X ” means that the location is the main location associated to the PySide.QtCore.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

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 QSettings.IniFormat as the first argument to the PySide.QtCore.QSettings constructor, followed by the scope, the organization name, and the application name:

settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                     "MySoft", "Star Runner")

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

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

class MainWindow(QMainWindow):
    ...
    def writeSettings(self):
        self.settings = QSettings("Moose Soft", "Clipper")
        self.settings.beginGroup("MainWindow")
        self.settings.setValue("size", self.size())
        self.settings.setValue("pos", self.pos())
        self.settings.endGroup()

    def readSettings(self):
        self.settings = QSettings("Moose Soft", "Clipper")
        self.settings.beginGroup("MainWindow")
        self.resize(settings.value("size", QSize(400, 400)).toSize())
        self.move(settings.value("pos", QPoint(200, 200)).toPoint())
        self.settings.endGroup()

See Window Geometry for a discussion on why it is better to call QWidget.resize() and QWidget.move() rather than QWidget.setGeometry() to restore a window’s geometry.

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

def __init__(self):
    self.settings = None
...
    self.readSettings()


# event : QCloseEvent
def closeEvent(self, event):
    if self.userReallyWantsToQuit():
        self.writeSettings()
        event.accept()
    else:
        event.ignore()

See the Application example for a self-contained example that uses PySide.QtCore.QSettings .

Accessing Settings from Multiple Threads or Processes Simultaneously

PySide.QtCore.QSettings is reentrant . This means that you can use distinct PySide.QtCore.QSettings object in different threads simultaneously. This guarantee stands even when the PySide.QtCore.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 PySide.QtCore.QSettings object, the change will immediately be visible in any other PySide.QtCore.QSettings objects that operate on the same location and that live in the same process.

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

Platform-Specific Notes

Locations Where Application Settings Are Stored

As mentioned in the Fallback Mechanism section, PySide.QtCore.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:

On Mac OS X versions 10.2 and 10.3, these files are used by default:

On Windows, NativeFormat settings are stored in the following registry paths:

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 IniFormat , the following files are used on Unix and Mac OS X:

On Windows, the following files are used:

The %APPDATA% path is usually C:\Documents and Settings\*User Name*\Application Data ; the %COMMON_APPDATA% path is usually C:\Documents and Settings\All Users\Application Data .

The paths for the .ini and .conf files can be changed using PySide.QtCore.QSettings.setPath() . On Unix and Mac OS X, the user can override them by by setting the XDG_CONFIG_HOME environment variable; see PySide.QtCore.QSettings.setPath() 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 PySide.QtCore.QSettings constructor that takes a file name as first argument and pass QSettings.IniFormat as second argument. For example:

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

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

On Mac OS X, you can access XML-based .plist files by passing QSettings.NativeFormat as second argument. For example:

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

Accessing the Windows Registry Directly

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

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 PySide.QtCore.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 PySide.QtCore.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 PySide.QtCore.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 the NativeFormat .

  • On Mac OS X, PySide.QtCore.QSettings.allKeys() will return some extra keys for global settings that apply to all applications. These keys can be read using PySide.QtCore.QSettings.value() but cannot be changed, only shadowed. Calling setFallbacksEnabled(false) will hide these global settings.

  • On Mac OS X, the CFPreferences API used by PySide.QtCore.QSettings expects Internet domain names rather than organization names. To provide a uniform API, PySide.QtCore.QSettings derives a fake domain name from the organization name (unless the organization name already is a domain name, e.g. OpenOffice.org). The algorithm appends ”.com” to the company name and replaces spaces and other illegal characters with hyphens. If you want to specify a different domain name, call QCoreApplication.setOrganizationDomain() , QCoreApplication.setOrganizationName() , and QCoreApplication.setApplicationName() in your main() function and then use the default PySide.QtCore.QSettings constructor. Another solution is to use preprocessor directives, for example:

    #ifdef Q_WS_MAC
        settings = QSettings("grenoullelogique.fr", "Squash")
    #else
        settings = QSettings("Grenoulle Logique", "Squash")
    #endif
  • On Unix and Mac OS X systems, the advisory file locking is disabled if NFS (or AutoFS or CacheFS) is detected to work around a bug in the NFS fcntl() implementation, which hangs forever if statd or lockd aren’t running. Also, the locking isn’t performed when accessing .plist files.

See also

PySide.QtCore.QVariant PySide.QtGui.QSessionManager Settings Editor Example Application Example

class PySide.QtCore.QSettings([parent=None])
class PySide.QtCore.QSettings(format, scope, organization[, application=""[, parent=None]])
class PySide.QtCore.QSettings(scope, organization[, application=""[, parent=None]])
class PySide.QtCore.QSettings(fileName, format[, parent=None])
class PySide.QtCore.QSettings(organization[, application=""[, parent=None]])
Parameters:

Constructs a PySide.QtCore.QSettings object for accessing settings of the application and organization set previously with a call to QCoreApplication.setOrganizationName() , QCoreApplication.setOrganizationDomain() , and QCoreApplication.setApplicationName() .

The scope is QSettings.UserScope and the format is PySide.QtCore.QSettings.defaultFormat() ( QSettings.NativeFormat by default). Use PySide.QtCore.QSettings.setDefaultFormat() 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 QCoreApplication.setOrganizationName() and QCoreApplication.setApplicationName() has not been previously called, the PySide.QtCore.QSettings object will not be able to read or write any settings, and PySide.QtCore.QSettings.status() will return AccessError .

On Mac OS X, if both a name and an Internet domain are specified for the organization, the domain is preferred over the name. On other platforms, the name is preferred over the domain.

Constructs a PySide.QtCore.QSettings object for accessing settings of the application called application from the organization called organization , and with parent parent .

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

If format is QSettings.NativeFormat , the native API is used for storing settings. If format is QSettings.IniFormat , the INI format is used.

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

Constructs a PySide.QtCore.QSettings object for accessing settings of the application called application from the organization called organization , and with parent parent .

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

The storage format is set to QSettings.NativeFormat (i.e. calling PySide.QtCore.QSettings.setDefaultFormat() before calling this constructor has no effect).

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

Constructs a PySide.QtCore.QSettings object for accessing the settings stored in the file called fileName , with parent parent . If the file doesn’t already exist, it is created.

If format is QSettings.NativeFormat , the meaning of fileName depends on the platform. On Unix, fileName is the name of an INI file. On Mac OS X, fileName is the name of a .plist file. On Windows, fileName is a path in the system registry.

If format is QSettings.IniFormat , fileName is the name of an INI file.

Warning

This function is provided for convenience. It works well for accessing INI or .plist files generated by Qt, but might fail on some syntaxes found in such files originated by other programs. In particular, be aware of the following limitations:

  • PySide.QtCore.QSettings provides no way of reading INI “path” entries, i.e., entries with unescaped slash characters. (This is because these entries are ambiguous and cannot be resolved automatically.)
  • In INI files, PySide.QtCore.QSettings uses the @ character as a metacharacter in some contexts, to encode Qt-specific data types (e.g., @Rect), and might therefore misinterpret it when it occurs in pure INI files.

Constructs a PySide.QtCore.QSettings object for accessing settings of the application called application from the organization called organization , and with parent parent .

Example:

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

The scope is set to QSettings.UserScope , and the format is set to QSettings.NativeFormat (i.e. calling PySide.QtCore.QSettings.setDefaultFormat() before calling this constructor has no effect).

See also

PySide.QtCore.QSettings.setDefaultFormat() Fallback Mechanism

PySide.QtCore.QSettings.Format

This enum type specifies the storage format used by PySide.QtCore.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 Mac OS X, this means the CFPreferences API; on Unix, this means textual configuration files in INI format.
QSettings.IniFormat Store the settings in INI files.
QSettings.InvalidFormat Special value returned by registerFormat() .

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

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 PySide.QtCore.QVariant can’t convert to PySide.QtCore.QString (e.g., PySide.QtCore.QPoint , PySide.QtCore.QRect , and PySide.QtCore.QSize ), 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

    PySide.QtCore.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 the 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, PySide.QtCore.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), call PySide.QtCore.QSettings.setIniCodec() .

See also

registerFormat() PySide.QtCore.QSettings.setPath()

PySide.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).
PySide.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.
PySide.QtCore.QSettings.allKeys()
Return type:list of strings

Returns a list of all keys, including subkeys, that can be read using the PySide.QtCore.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 PySide.QtCore.QSettings.beginGroup() , only the keys in the group are returned, without the group prefix:

settings.beginGroup("fridge")
keys = settings.allKeys()
# keys: ["color", "size"]
PySide.QtCore.QSettings.applicationName()
Return type:unicode

Returns the application name used for storing the settings.

PySide.QtCore.QSettings.beginGroup(prefix)
Parameters:prefix – unicode

Appends prefix to the current group.

The current group is automatically prepended to all keys specified to PySide.QtCore.QSettings . In addition, query functions such as PySide.QtCore.QSettings.childGroups() , PySide.QtCore.QSettings.childKeys() , and PySide.QtCore.QSettings.allKeys() are based on the group. By default, no group is set.

Groups are useful to avoid typing in the same setting paths over and over. For example:

settings.beginGroup("mainwindow")
settings.setValue("size", win.size())
settings.setValue("fullScreen", win.isFullScreen())
settings.endGroup()

settings.beginGroup("outputpanel")
settings.setValue("visible", panel.isVisible())
settings.endGroup()

This will set the value of three settings:

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

Call PySide.QtCore.QSettings.endGroup() to reset the current group to what it was before the corresponding PySide.QtCore.QSettings.beginGroup() call. Groups can be nested.

PySide.QtCore.QSettings.beginReadArray(prefix)
Parameters:prefix – unicode
Return type:PySide.QtCore.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 PySide.QtCore.QSettings.beginWriteArray() to write the array in the first place.

PySide.QtCore.QSettings.beginWriteArray(prefix[, size=-1])
Parameters:
  • prefix – unicode
  • sizePySide.QtCore.int

Adds prefix to the current group and starts writing an array of size size . If size is -1 (the default), it is automatically determined based on the indexes of the entries written.

If you have many occurrences of a certain set of keys, you can use arrays to make your life easier. For example, let’s suppose that you want to save a variable-length list of user names and passwords. You could then write:

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 PySide.QtCore.QSettings.beginReadArray() .

PySide.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 PySide.QtCore.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 PySide.QtCore.QSettings.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 PySide.QtCore.QSettings.childKeys() and PySide.QtCore.QSettings.childGroups() recursively.

PySide.QtCore.QSettings.childKeys()
Return type:list of strings

Returns a list of all top-level keys that can be read using the PySide.QtCore.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 PySide.QtCore.QSettings.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 PySide.QtCore.QSettings.childKeys() and PySide.QtCore.QSettings.childGroups() recursively.

PySide.QtCore.QSettings.clear()

Removes all entries in the primary location associated to this PySide.QtCore.QSettings object.

Entries in fallback locations are not removed.

If you only want to remove the entries in the current PySide.QtCore.QSettings.group() , use remove(“”) instead.

PySide.QtCore.QSettings.contains(key)
Parameters:key – unicode
Return type:PySide.QtCore.bool

Returns true if there exists a setting called key ; returns false otherwise.

If a group is set using PySide.QtCore.QSettings.beginGroup() , key is taken to be relative to that group.

Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.

static PySide.QtCore.QSettings.defaultFormat()
Return type:PySide.QtCore.QSettings.Format

Returns default file format used for storing settings for the PySide.QtCore.QSettings ( PySide.QtCore.QObject *) constructor. If no default format is set, QSettings.NativeFormat is used.

PySide.QtCore.QSettings.endArray()

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

PySide.QtCore.QSettings.endGroup()

Resets the group to what it was before the corresponding PySide.QtCore.QSettings.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() == ""
PySide.QtCore.QSettings.fallbacksEnabled()
Return type:PySide.QtCore.bool

Returns true if fallbacks are enabled; returns false otherwise.

By default, fallbacks are enabled.

PySide.QtCore.QSettings.fileName()
Return type:unicode

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

On Windows, if the format is QSettings.NativeFormat , the return value is a system registry path, not a file path.

PySide.QtCore.QSettings.format()
Return type:PySide.QtCore.QSettings.Format

Returns the format used for storing the settings.

PySide.QtCore.QSettings.group()
Return type:unicode

Returns the current group.

PySide.QtCore.QSettings.iniCodec()
Return type:PySide.QtCore.QTextCodec

Returns the codec that is used for accessing INI files. By default, no codec is used, so a null pointer is returned.

PySide.QtCore.QSettings.isWritable()
Return type:PySide.QtCore.bool

Returns true if settings can be written using this PySide.QtCore.QSettings object; returns false otherwise.

One reason why PySide.QtCore.QSettings.isWritable() might return false is if PySide.QtCore.QSettings operates on a read-only file.

Warning

This function is not perfectly reliable, because the file permissions can change at any time.

PySide.QtCore.QSettings.organizationName()
Return type:unicode

Returns the organization name used for storing the settings.

PySide.QtCore.QSettings.remove(key)
Parameters:key – unicode

Removes the setting key and any sub-settings of key .

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 PySide.QtCore.QSettings.remove() .

If key is an empty string, all keys in the current PySide.QtCore.QSettings.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"]

Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.

PySide.QtCore.QSettings.scope()
Return type:PySide.QtCore.QSettings.Scope

Returns the scope used for storing the settings.

PySide.QtCore.QSettings.setArrayIndex(i)
Parameters:iPySide.QtCore.int

Sets the current array index to i . Calls to functions such as PySide.QtCore.QSettings.setValue() , PySide.QtCore.QSettings.value() , PySide.QtCore.QSettings.remove() , and PySide.QtCore.QSettings.contains() will operate on the array entry at that index.

You must call PySide.QtCore.QSettings.beginReadArray() or PySide.QtCore.QSettings.beginWriteArray() before you can call this function.

static PySide.QtCore.QSettings.setDefaultFormat(format)
Parameters:formatPySide.QtCore.QSettings.Format

Sets the default file format to the given format , which is used for storing settings for the PySide.QtCore.QSettings ( PySide.QtCore.QObject *) constructor.

If no default format is set, QSettings.NativeFormat is used. See the documentation for the PySide.QtCore.QSettings constructor you are using to see if that constructor will ignore this function.

PySide.QtCore.QSettings.setFallbacksEnabled(b)
Parameters:bPySide.QtCore.bool

Sets whether fallbacks are enabled to b .

By default, fallbacks are enabled.

PySide.QtCore.QSettings.setIniCodec(codec)
Parameters:codecPySide.QtCore.QTextCodec

Sets the codec for accessing INI files (including .conf files on Unix) to codec . The codec is used for decoding any data that is read from the INI file, and for encoding any data that is written to the file. By default, no codec is used, and non-ASCII characters are encoded using standard INI escape sequences.

Warning

The codec must be set immediately after creating the PySide.QtCore.QSettings object, before accessing any data.

PySide.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 the PySide.QtCore.QTextCodec for the encoding specified by codecName . Common values for codecName include “ISO 8859-1”, “UTF-8”, and “UTF-16”. If the encoding isn’t recognized, nothing happens.

static PySide.QtCore.QSettings.setPath(format, scope, path)
Parameters:

Sets the path used for storing settings for the given format and scope , to path . The format can be a custom format.

The table below summarizes the default values:

Platform Format Scope Path
Windows IniFormat UserScope %APPDATA%
SystemScope %COMMON_APPDATA%
Unix NativeFormat , IniFormat UserScope $HOME/.config
SystemScope /etc/xdg
Qt for Embedded Linux NativeFormat , IniFormat UserScope $HOME/Settings
SystemScope /etc/xdg
Mac OS X IniFormat UserScope $HOME/.config
SystemScope /etc/xdg

The default UserScope paths on Unix and Mac OS X ($HOME/.config or $HOME/Settings) can be overridden by the user by setting the XDG_CONFIG_HOME environment variable. The default SystemScope paths on Unix and Mac OS X (/etc/xdg ) can be overridden when building the Qt library using the configure script’s --sysconfdir flag (see PySide.QtCore.QLibraryInfo for details).

Setting the NativeFormat paths on Windows and Mac OS X has no effect.

Warning

This function doesn’t affect existing PySide.QtCore.QSettings objects.

See also

registerFormat()

PySide.QtCore.QSettings.setValue(key, value)
Parameters:
  • key – unicode
  • value – object

Sets the value of setting key to value . If the key already exists, the previous value is overwritten.

Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X 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
PySide.QtCore.QSettings.status()
Return type:PySide.QtCore.QSettings.Status

Returns a status code indicating the first error that was met by PySide.QtCore.QSettings , or QSettings.NoError if no error occurred.

Be aware that PySide.QtCore.QSettings delays performing some operations. For this reason, you might want to call PySide.QtCore.QSettings.sync() to ensure that the data stored in PySide.QtCore.QSettings is written to disk before calling PySide.QtCore.QSettings.status() .

PySide.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 PySide.QtCore.QSettings ‘s destructor and by the event loop at regular intervals, so you normally don’t need to call it yourself.

PySide.QtCore.QSettings.value(key[, defaultValue=None])
Parameters:
  • key – unicode
  • defaultValue – object
Return type:

object

Returns the value for setting key . If the setting doesn’t exist, returns defaultValue .

If no default value is specified, a default PySide.QtCore.QVariant is returned.

Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.

Example:

settings = QSettings()
settings.setValue("animal/snake", 58)
settings.value("animal/snake", 1024)   # returns 58
settings.value("animal/zebra", 1024)   # returns 1024
settings.value("animal/zebra")         # returns 0

Warning

QSettings.value can return different types (QVariant types) depending on the platform it’s running on, so the safest way to use it is always casting the result to the desired type, e.g.: int(settings.value(“myKey”))