6.0.0-rc4Source

QSettings Class

The QSettings class provides persistent platform-independent application settings. More…

Header#include <QSettings>
CMaketarget_link_libraries(app PRIVATE Nt::Core)
ModuleNt Core C++ Classes
InheritsQObject

List of all members, including inherited members

Public Types

enumStatus
enumFormat
enumScope
typedefSettingsMap
typedefReadFunc
typedefWriteFunc

Public Functions

QSettings(const QString &organization, const QString &application = QString(), QObject *parent = nullptr)
QSettings(Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = nullptr)
QSettings(Format format, Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = nullptr)
QSettings(const QString &fileName, Format format, QObject *parent = nullptr)
QSettings(QObject *parent = nullptr)
QSettings(Scope scope, QObject *parent = nullptr)
~QSettings()
voidclear()
voidsync()
Statusstatus() const
boolisAtomicSyncRequired() const
voidsetAtomicSyncRequired(bool enable)
voidbeginGroup(const QString &prefix)
voidendGroup()
QStringgroup() const
intbeginReadArray(const QString &prefix)
voidbeginWriteArray(const QString &prefix, int size = -1)
voidendArray()
voidsetArrayIndex(int i)
QStringListallKeys() const
QStringListchildKeys() const
QStringListchildGroups() const
boolisWritable() const
voidsetValue(const QString &key, const QVariant &value)
QVariantvalue(const QString &key) const
QVariantvalue(const QString &key, const QVariant &defaultValue) const
voidremove(const QString &key)
boolcontains(const QString &key) const
voidsetFallbacksEnabled(bool b)
boolfallbacksEnabled() const
QStringfileName() const
Formatformat() const
Scopescope() const
QStringorganizationName() const
QStringapplicationName() const

Static Public Members

voidsetDefaultFormat(Format format)
FormatdefaultFormat()
voidsetPath(Format format, Scope scope, const QString &path)
FormatregisterFormat(const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive)

Reimplemented Protected Functions

boolevent(QEvent *event)

Detailed Description

Users expect applications to remember their settings (window sizes and positions, options, and so on) across sessions. QSettings stores them in a file, and a setting is a key and a QVariant. Keys are strings that can be grouped with /, like the path of a file.

QCoreApplication::setOrganizationName("MySoft");
QCoreApplication::setApplicationName("Star Runner");

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

Locations

QSettings(const QString &organization, const QString &application) and the constructors that depend on QCoreApplication use these files on Linux, in the order in which they are searched. $XDG_CONFIG_HOME defaults to ~/.config, and $XDG_CONFIG_DIRS to /etc/xdg. The extension is .conf for NativeFormat and .ini for IniFormat.

  1. $XDG_CONFIG_HOME/MySoft/Star Runner.conf (user scope only)

  2. $XDG_CONFIG_HOME/MySoft.conf (user scope only)

  3. /etc/xdg/MySoft/Star Runner.conf

  4. /etc/xdg/MySoft.conf

A value that is not found in the first file is looked up in the next ones, unless setFallbacksEnabled() turns that off. Settings are always written to the first file; the directories are created as needed. The organization-wide files let several applications share settings. If the organization name is empty, status() is AccessError and the files are placed under the name "Unknown Organization". A QSettings can also use one explicit file (QSettings(const QString &fileName, Format format)); the file name must be given in a format that can be read, as NativeFormat and IniFormat are both the INI format on Linux. setPath() changes the directories, and setDefaultFormat() the format of the constructors that take none.

Groups and arrays

beginGroup() and endGroup() add a prefix to every key. beginWriteArray() and beginReadArray() store lists of structures as prefix/1/key, prefix/2/key and so on, with prefix/size; setArrayIndex() selects the element, counting from 0.

int size = settings.beginReadArray("logins");
for (int i = 0; i < size; ++i) {
    settings.setArrayIndex(i);
    QString user = settings.value("userName").toString();
}
settings.endArray();

Writing

Changes are kept in memory, so that every QSettings object of the process that uses the same file sees them at once. They are written to the file when the event loop runs, when sync() is called, and when the object is destroyed. The write takes the lock file <file>.lock with QLockFile, reads the file again if another process changed it, applies the changes made by this process on top, and replaces the file with QSaveFile, so that readers never see a partial file and writers do not lose each other's changes. sync() also reads the file again if it changed.

The INI format

[General]
size=@Size(800 600)
title=Star Runner

[editor]
wrapMargin=68
recent=a.txt, b.txt

Keys without a group are in the section [General]; a key a/b/c is the key c in the section called a/b, which is written with a backslash in place of the slash. Characters in group and key names other than letters, digits and _-. are written as %XX (or %UXXXX), so My Group becomes My%20Group. Values of type QString, the integer types, bool and the floating-point types are written as text, and are read back as QString: use toInt() and the like. A string that contains ,, ; or =, or begins or ends with a blank, is quoted; backslashes, double quotes and control characters are escaped, and non-ASCII characters are UTF-8. A QStringList is written as comma-separated items and read back as a QStringList when it has several, an empty one is written as @Invalid() and read back as an invalid QVariant, and a QVariantList is written the same way but is read as a QStringList, or as a QVariantList when an item has a special form. A QByteArray is @ByteArray(...), QPoint, QSize and QRect are @Point(x y), @Size(w h) and @Rect(x y w h), a QDateTime is @DateTime(...), and any other type is @Variant(...) with the bytes of its QDataStream form (version Qt_4_0), with unprintable bytes escaped. A string that begins with @ gets a second one. The file is read as Qt reads it: a line that begins with ; is a comment, and so is the rest of a line after a ; that is not quoted; a backslash at the end of a line continues it; blanks around keys, values and list items are ignored.

Keys and sections are case-sensitive in the INI format. A section named General (in any case) holds the keys without a group; a group called General is written as [%General]. Settings are written sorted, with General first, so the output is deterministic.

Custom formats

registerFormat() adds a format that is read and written by functions of your own, using a SettingsMap of full keys:

static bool readXml(QIODevice &device, QSettings::SettingsMap &map);
static bool writeXml(QIODevice &device, const QSettings::SettingsMap &map);

const QSettings::Format XmlFormat = QSettings::registerFormat("xml", readXml, writeXml);
QSettings settings(XmlFormat, QSettings::UserScope, "MySoft", "Star Runner");

Thread safety

QSettings objects are reentrant: different objects, in different threads or different processes, may use the same file. Each object must be used from one thread at a time.

See also QVariant, QSaveFile, QLockFile and QStandardPaths.

Differences from Qt

The keys and group names are const QString & and not QAnyStringView. The registry formats Registry32Format and Registry64Format are only enumerators: on Linux they make status() return AccessError, as does any unregistered custom format. NativeFormat is the INI format, and the macOS property lists are not supported. The keys of the INI format are case-sensitive on every platform. A line that begins with # in an INI file is also taken for a comment. The default directories are read from the environment (XDG_CONFIG_HOME and XDG_CONFIG_DIRS) each time a QSettings object is constructed, not once. There is no setSystemIniPath() or setUserIniPath(), which Qt 6 removed. The sections of an INI file are read at once, not when first used. A @Variant() value is only restored if the stream operators of the type are registered. A type without stream operators, such as the QJsonValue family, is not stored: setValue() keeps it in memory, but a warning is printed when the file is written and the setting is written as @Invalid(). Comments and the order of the keys of an INI file are not preserved when it is rewritten. A QSettings object is not thread-safe itself, and QSettings::value() on a file that another process is replacing sees either the old or the new file, never part of both.

On Zephyr the default locations do not exist, so construct the settings with a file name on a mounted file system. See Nt on Zephyr.

Member Type Documentation

enum QSettings::Format

The storage format of the settings.

ConstantDescription
QSettings::NativeFormatThe platform's native format. On Linux this is the INI format with the file extension .conf.
QSettings::IniFormatThe INI format, with the file extension .ini.
QSettings::Registry32FormatThe 32-bit Windows registry. Not available: using it makes status() return AccessError.
QSettings::Registry64FormatThe 64-bit Windows registry. Not available: using it makes status() return AccessError.
QSettings::InvalidFormatThe value returned by registerFormat() when no format can be registered; a QSettings object with this format cannot read or write.
QSettings::CustomFormat1The first format registered with registerFormat().
QSettings::CustomFormat2The second format registered with registerFormat().
QSettings::CustomFormat3The third format registered with registerFormat().
QSettings::CustomFormat4The fourth format registered with registerFormat().
QSettings::CustomFormat5The fifth format registered with registerFormat().
QSettings::CustomFormat6The sixth format registered with registerFormat().
QSettings::CustomFormat7The seventh format registered with registerFormat().
QSettings::CustomFormat8The eighth format registered with registerFormat().
QSettings::CustomFormat9The ninth format registered with registerFormat().
QSettings::CustomFormat10The tenth format registered with registerFormat().
QSettings::CustomFormat11The eleventh format registered with registerFormat().
QSettings::CustomFormat12The twelfth format registered with registerFormat().
QSettings::CustomFormat13The thirteenth format registered with registerFormat().
QSettings::CustomFormat14The fourteenth format registered with registerFormat().
QSettings::CustomFormat15The fifteenth format registered with registerFormat().
QSettings::CustomFormat16The sixteenth format registered with registerFormat().

typedef QSettings::ReadFunc

A function that reads a custom format from device into map and returns true on success.

enum QSettings::Scope

Whether the settings belong to the current user or to all users of the system.

ConstantDescription
QSettings::UserScopeStore the settings in the current user's configuration directory.
QSettings::SystemScopeStore the settings in the system-wide configuration directory.

typedef QSettings::SettingsMap

The type of the map that a custom format reads and writes: every setting by its full key (the group names and the key joined with /).

enum QSettings::Status

The status of a QSettings object after the last operation.

ConstantDescription
QSettings::NoErrorNo error occurred.
QSettings::AccessErrorAn access error occurred: a file could not be opened, read or written, the organization name is missing, or the format is not usable.
QSettings::FormatErrorA format error occurred, for instance a malformed INI file or a custom format function that failed.

typedef QSettings::WriteFunc

A function that writes map to device in a custom format and returns true on success.

Member Function Documentation

[explicit] QSettings::QSettings(const QString &organization, const QString &application = QString(), QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings of the application called application from the organization called organization, with the given parent. The settings are those of the current user, in the default format.

If application is empty, only the organization-wide settings are accessed.

See also setDefaultFormat(), setPath() and fileName().

QSettings::QSettings(Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings of the application called application from the organization called organization, in the given scope, with the given parent.

See also setDefaultFormat().

QSettings::QSettings(Format format, Scope scope, const QString &organization, const QString &application = QString(), QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings of the application called application from the organization called organization, in the given format and scope, with the given parent.

If the format is not usable, status() returns AccessError and nothing can be read or written.

See also Format and Scope.

QSettings::QSettings(const QString &fileName, Format format, QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings stored in the file called fileName, with the given parent. If the file does not exist, it is created when the settings are written. The format is the way the file is read and written; NativeFormat and IniFormat are the same here.

See also fileName().

[explicit] QSettings::QSettings(QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings of the application, with the given parent. The organization name is QCoreApplication::organizationName(), or QCoreApplication::organizationDomain() if it is empty, and the application name is QCoreApplication::applicationName(). The settings are those of the current user, in the default format.

See also setDefaultFormat().

[explicit] QSettings::QSettings(Scope scope, QObject *parent = nullptr)

Constructs a QSettings object for accessing the settings of the application in the given scope, with the given parent. The organization and application names are those of QCoreApplication.

See also QSettings().

[override] QSettings::~QSettings()

Writes any unsaved changes to permanent storage, and destroys the object.

See also sync().

QStringList QSettings::allKeys() const

Returns a list of all keys, including subkeys, that can be read using the QSettings object.

Example:

settings.setValue("fridge/color", QColor(Qt::white));
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", true);
settings.setValue("tv", false);

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

If a group is set using beginGroup(), only the keys in the group are returned, without the group prefix. The list is sorted.

See also childGroups() and childKeys().

QString QSettings::applicationName() const

Returns the application name used for storing the settings, as given to the constructor. It is empty for a QSettings that uses a file name.

See also QCoreApplication::applicationName(), format(), scope() and organizationName().

void QSettings::beginGroup(const QString &prefix)

Appends prefix to the current group.

The current group is automatically prepended to all keys specified to QSettings. In addition, query functions such as childGroups(), childKeys() and 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("pos", win->pos());
settings.endGroup();

See also endGroup() and group().

int QSettings::beginReadArray(const QString &prefix)

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

int size = settings.beginReadArray("logins");
for (int i = 0; i < size; ++i) {
    settings.setArrayIndex(i);
    QString user = settings.value("userName").toString();
}
settings.endArray();

Use beginWriteArray() to write the array in the first place.

See also beginWriteArray(), endArray() and setArrayIndex().

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

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 list of users consisting of user name and password fields. You could then write:

struct Login {
    QString userName;
    QString password;
};
QList<Login> logins;

QSettings settings;
settings.beginWriteArray("logins");
for (int i = 0; i < logins.size(); ++i) {
    settings.setArrayIndex(i);
    settings.setValue("userName", logins.at(i).userName);
    settings.setValue("password", logins.at(i).password);
}
settings.endArray();

The elements are stored as logins/1/userName and so on, and the size as logins/size.

See also beginReadArray(), endArray() and setArrayIndex().

QStringList QSettings::childGroups() const

Returns a list of all key top-level groups that contain keys that can be read using the QSettings object. The list is sorted.

See also childKeys() and allKeys().

QStringList QSettings::childKeys() const

Returns a list of all top-level keys that can be read using the QSettings object. The list is sorted.

See also allKeys() and childGroups().

void 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 remove() and setFallbacksEnabled().

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

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

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

See also value() and setValue().

[static] Format QSettings::defaultFormat()

Returns default file format used for storing settings for the QSettings(const QString &organization, const QString &application, QObject *parent) constructor. If no default format is set, QSettings::NativeFormat is used.

See also setDefaultFormat().

void QSettings::endArray()

Closes the array that was started using beginReadArray() or beginWriteArray(). A warning is printed if there is no matching begin.

See also beginReadArray() and beginWriteArray().

void QSettings::endGroup()

Resets the group to what it was before the corresponding beginGroup() call. A warning is printed if there is no matching beginGroup().

See also beginGroup() and group().

[override, protected] bool QSettings::event(QEvent *event)

Reimplements QObject::event().

Writes the unsaved changes when the object receives the update request that it posts to itself after a change.

bool QSettings::fallbacksEnabled() const

Returns true if fallbacks are enabled; returns false otherwise.

By default, fallbacks are enabled.

See also setFallbacksEnabled().

QString QSettings::fileName() const

Returns the path where settings written using this QSettings object are stored: the absolute path of the primary file.

See also isWritable() and format().

Format QSettings::format() const

Returns the format used for storing the settings.

See also defaultFormat(), fileName() and scope().

QString QSettings::group() const

Returns the current group, without a trailing slash.

See also beginGroup() and endGroup().

bool QSettings::isAtomicSyncRequired() const

Returns true if QSettings is only allowed to perform atomic saving and reloading (synchronization) of the settings; otherwise returns false. The default is true.

See also setAtomicSyncRequired().

bool QSettings::isWritable() const

Returns true if settings can be written using this QSettings object; returns false otherwise. This is the case if the primary file can be written, or created, and the format can write.

See also status() and sync().

QString QSettings::organizationName() const

Returns the organization name used for storing the settings, as given to the constructor. It is empty for a QSettings that uses a file name.

See also QCoreApplication::organizationName(), format(), scope() and applicationName().

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

Registers a custom storage format. On success, returns a special Format value that can then be passed to the QSettings constructors. On failure, returns InvalidFormat: at most 16 custom formats can be registered.

The extension is the suffix of the files of the format, without the dot. The readFunc and writeFunc read and write a file as a SettingsMap of full keys; they return true on success, and the QSettings object reports FormatError otherwise. caseSensitivity tells whether the keys of the format are case-sensitive. The functions may be called from any thread, at any time, with the file locked against other writers.

See also setPath().

void QSettings::remove(const QString &key)

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

Example:

settings.setValue("ape", 0);
settings.setValue("monkey", 1);
settings.setValue("monkey/sea", 2);
settings.setValue("monkey/doe", 4);

settings.remove("monkey");
QStringList 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 remove().

If key is an empty string, all keys in the current group() are removed.

See also clear(), setValue(), value() and contains().

Scope QSettings::scope() const

Returns the scope used for storing the settings.

See also format(), organizationName() and applicationName().

void QSettings::setArrayIndex(int i)

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

You must call beginReadArray() or beginWriteArray() before you can call this function. Note that the indexes in the file start at 1, not 0.

See also beginReadArray() and beginWriteArray().

void QSettings::setAtomicSyncRequired(bool enable)

Configures whether QSettings is required to use atomic saving and reloading (synchronization) of the settings, according to enable.

If it is not required, and the directory of the file cannot be written (so that no temporary file can be created), the file is written in place, which is not atomic.

See also isAtomicSyncRequired().

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

Sets the default file format to the given format, which is used for storing settings for the QSettings(const QString &organization, const QString &application, QObject *parent) constructor. If no default format is set, QSettings::NativeFormat is used.

See also defaultFormat() and format().

void QSettings::setFallbacksEnabled(bool b)

Sets whether fallbacks are enabled to b.

By default, fallbacks are enabled: a key that is not in the primary file is looked up in the organization-wide and system-wide files.

See also fallbacksEnabled().

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

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

Without a path set, the user scope uses $XDG_CONFIG_HOME (or ~/.config) and the system scope uses the directories of $XDG_CONFIG_DIRS (or /etc/xdg). A path set for IniFormat is also used by the other formats that have none of their own.

This function does not affect QSettings objects that already exist.

See also QSettings().

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

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

Keys are case-sensitive in the INI format, but not in every custom format or in Qt on some platforms: to stay portable, always refer to a key with the same case and avoid keys that differ only by case. An empty key is refused with a warning.

See also value(), remove() and contains().

Status QSettings::status() const

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

See also Status.

void 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 the event loop after settings have been set, and from the destructor, so you should not normally need to call it.

See also status().

QVariant QSettings::value(const QString &key) const

Returns the value for setting key, or an invalid QVariant if the setting does not exist.

See also setValue() and contains().

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

This is an overloaded function.

Returns the value for setting key. If the setting does not exist, returns defaultValue.

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

The settings are looked up in the primary file and then in the fallback ones, unless fallbacksEnabled() is false. A value read from a file is a QString, a QStringList, a QByteArray or whatever its @Variant() form encodes; convert it with toInt() and the like.

See also setValue(), contains() and remove().