Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# QCoreSettings Class Reference

The QCoreSettings class provides persistent platform-independent application settings. More...

    #include <QCoreSettings>

Inherits QObject.

Inherited by QSettings.

- List of all members, including inherited members

### Public Types

- enum Status { NoError, AccessError, FormatError }

### Writable Properties

- 1 writable property inherited from QObject

### Public Functions

- QCoreSettings ( const QString & organization, const QString & application = QString(), QObject * parent = 0 )
- QCoreSettings ( Qt::SettingsScope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0 )
- QCoreSettings ( Qt::SettingsFormat format, Qt::SettingsScope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0 )
- QCoreSettings ( const QString & fileName, Qt::SettingsFormat format, QObject * parent = 0 )
- QCoreSettings ( QObject * parent = 0 )
- ~QCoreSettings ()
- QStringList allKeys () const
- void beginGroup ( const QString & prefix )
- int beginReadArray ( const QString & prefix )
- void beginWriteArray ( const QString & prefix, int size = -1 )
- QStringList childGroups () const
- QStringList childKeys () const
- void clear ()
- bool contains ( const QString & key ) const
- void endArray ()
- void endGroup ()
- bool fallbacksEnabled () const
- QString fileName () const
- QString group () const
- bool isWritable () const
- void remove ( const QString & key )
- void setArrayIndex ( int i )
- void setFallbacksEnabled ( bool b )
- void setValue ( const QString & key, const QCoreVariant & value )
- Status status () const
- void sync ()
- QCoreVariant value ( const QString & key, const QCoreVariant & defaultValue = QCoreVariant() ) const

- 24 public functions inherited from QObject

### Public Slots

- 1 public slot inherited from QObject

### Signals

- 1 signal inherited from QObject

### Static Public Members

- 4 static public members inherited from QObject

### Protected Functions

- 9 protected functions inherited from QObject

## Detailed Description

The QCoreSettings 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 X11 and embedded Linux, in the absense of a standard, many applications (including the KDE applications) use INI text files.

QCoreSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner.

If your application links against the QtGui library, you can use QSettings rather than QCoreSettings. QSettings's API is based on QVariant instead of QCoreVariant, which allows you to save GUI-related types such as QRect, QSize, and QColor.

- Basic Usage
- Key Syntax
- Fallback Mechanism
- Restoring the State of a GUI Application
- Accessing Settings from Multiple Threads or Processes Simultaneously
- Platform-Specific Notes

### Basic Usage

When creating a QCoreSettings object, you must pass the domain name of your company or organization as well as the name of your application. For example, if your product is called DataMill and you own the software.org Internet domain name, you would construct the QCoreSettings object as follows:

        QCoreSettings settings("software.org", "DataMill");

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

If you use QCoreSettings from many places in your application, you might want to specify the organization domain name and the product name using QCoreApplication::setProductInfo() and use the default QCoreSettings constructor:

        qApp->setProductInfo("software.org", "DataMill");
        ...
        QCoreSettings settings;

QCoreSettings stores settings. Each setting consists of a QString that specifies the setting's name (the key) and a QCoreVariant that stores the data associated with the key. To write a setting, use setValue(). For example:

        settings.setValue("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("wrapMargin").toInt();

If there is no setting with the specified name, QCoreSettings returns a null QCoreVariant (which converts to the integer 0). You can specify another default value by passing a second argument to value():

        int margin = settings.value("wrapMargin", 80).toInt();

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

### 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 two simple rules:

1. Always refer to the same key using the same case. For example, if you refer to a key as "text fonts" in one place in your code, don't refer to it as "Text Fonts" elsewhere.
2. Avoid key names that are identical except for the case. For example, if you have a key called "MainWindow", don't try to save another key as "mainwindow".

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 many settings with the same prefix, you can specify the prefix using beginGroup() and call 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 beginGroup(), the behavior of most functions changes consequently. Groups can be set recursively.

In addition to groups, QCoreSettings also supports an "array" concept. See beginReadArray() and beginWriteArray() for details.

### Fallback Mechanism

Let's assume that you have created a QCoreSettings object with the organization domain name "software.org" and the application name "DataMill". When you look up a value, up to four locations are searched in that order:

1. a user-specific location for the DataMill application
2. a user-spefific location for all applications by software.org
3. a system-wide location for the DataMill application
4. a system-wide location for all applications by software.org

On Unix with X11 and on embedded Linux, these locations are the following files:

1. `$HOME/.qt4/software.org/DataMill.conf`
2. `$HOME/.qt4/software.org.conf`
3. `$QTDIR/.qt4/software.org/DataMill.conf`
4. `$QTDIR/.qt4/software.org.conf`

($QTDIR is the location where Qt is installed.)

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

1. `$HOME/Library/Preferences/org.software.DataMill.plist`
2. `$HOME/Library/Preferences/org.software.plist`
3. `/Library/Preferences/org.software.DataMill.plist`
4. `/Library/Preferences/org.software.plist`

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

1. `HKEY_CURRENT_USER\Software\software.org\DataMill`
2. `HKEY_CURRENT_USER\Software\software.org`
3. `HKEY_LOCAL_MACHINE\Software\software.org\DataMill`
4. `HKEY_LOCAL_MACHINE\Software\software.org`

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

Let's see with an example:

        QCoreSettings obj1("software.org", "DataMill");
        QCoreSettings obj2("software.org");
        QCoreSettings obj3(Qt::SystemScope, "software.org", "DataMill");
        QCoreSettings obj4(Qt::SystemScope, "software.org");

The table below summarizes which QCoreSettings objects access which location. "X" means that the location is the main location associated to the QCoreSettings 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 |  |  |
2. User, Organization | o | X |  |
3. System, Application | o |  | X |
4. 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 Qt::IniFormat as the first argument to the QCoreSettings constructor, followed by the scope, the organization domain name, and the application name:

        QCoreSettings settings(Qt::IniFormat, Qt::UserScope,
                               "software.org", "DataMill");

Sometimes you do want to access settings stored in a specific file or registry path. In that case, you can use a constructor that takes a file name (or registry path) and a file format. For example:

        QCoreSettings settings("datamill.ini", Qt::IniFormat);

The file format can either be Qt::IniFormat or Qt::NativeFormat. On Mac OS X, the native format is an XML-based format called plist. On Windows, the native format is the Windows registry, and the first argument is a path in the registry rather than a file name, for example:

        QCoreSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft",
                               Qt::NativeFormat);

On X11 and embedded Linux, Qt::IniFormat and Qt::NativeFormat have the same meaning.

### Restoring the State of a GUI Application

QCoreSettings is often used to store the state of a GUI application. The following example will illustrate how to use we will use QCoreSettings (actually, QSettings) to save and restore the geometry of an application's main window.

        void MainWindow::writeSettings()
        {
            QSettings settings("www.moose-soft.co.uk", "Clipper");

            settings.beginGroup("MainWindow");
            settings.setValue("size", size());
            settings.setValue("pos", pos());
            settings.endGroup();
        }

        void MainWindow::readSettings()
        {
            QSettings settings("www.moose-soft.co.uk", "Clipper");

            settings.beginGroup("MainWindow");
            resize(settings.value("size", QSize(400, 400)));
            move(settings.value("pos", QPoint(200, 200)));
            settings.endGroup();
        }

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

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

        MainWindow::MainWindow(QWidget *parent)
            : QMainWindow(parent)
        {
            ...
            readSettings();
        }

        void MainWindow::closeEvent(QCloseEvent *event)
        {
            if (userReallyWantsToQuit()) {
                writeSettings();
                event->accept();
            } else {
                event->ignore();
            }
        }

See the `gui/application` example provided in Qt's `example` directory for a self-contained example that uses QSettings.

### Accessing Settings from Multiple Threads or Processes Simultaneously

QCoreSettings is reentrant. This means that you can use distinct QCoreSettings object in different threads simultaneously. This guarantee stands even when the QCoreSettings objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through one QCoreSettings object, the change will immediately be visible in any other QCoreSettings object that operates on the same location and that lives in the same process.

QCoreSettings 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 a smart merging algorithm to ensure data integrity. Changes performed by another process aren't visible in the current process until sync() is called.

### Platform-Specific Notes

While QCoreSettings 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.
- On Mac OS X, allKeys() will return some extra keys for global settings that apply to all applications. These keys can be read using value() but cannot be change, only shadowed. You can hide these global settings by calling setFallbackEnabled(false).

See also QSettings and QSessionManager.

## Member Type Documentation

### enum QCoreSettings::Status

The following status values are possible:

`QCoreSettings::NoError` | No error occurred.
`QCoreSettings::AccessError` | An access error occurred (e.g. trying to write to a read-only file).
`QCoreSettings::FormatError` | A format error occurred (e.g. loading a malformed INI file).

See also status().

## Member Function Documentation

### QCoreSettings::QCoreSettings ( const QString & organization, const QString & application = QString(), QObject * parent = 0 )

Constructs a QCoreSettings object for accessing settings of the application called application from the organization with the Internet domain name organization, and with parent parent.

Example:

        QCoreSettings settings("www.technopro.co.jp", "Facturo-Pro");

The scope is Qt::UserScope and the format is Qt::NativeFormat.

See also Locations for Storing Settings.

### QCoreSettings::QCoreSettings ( Qt::SettingsScope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0 )

Constructs a QCoreSettings object for accessing settings of the application called application from the organization with the Internet domain name organization, and with parent parent.

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

The storage format is always Qt::NativeFormat.

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

### QCoreSettings::QCoreSettings ( Qt::SettingsFormat format, Qt::SettingsScope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0 )

Constructs a QCoreSettings object for accessing settings of the application called application from the organization with the Internet domain name organization, and with parent parent.

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

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

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

### QCoreSettings::QCoreSettings ( const QString & fileName, Qt::SettingsFormat format, QObject * parent = 0 )

Constructs a QCoreSettings 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 Qt::NativeFormat, the meaning of fileName depends on the platform. On Unix/X11, 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 Qt::IniFormat, fileName is the name of an INI file.

See also fileName().

### QCoreSettings::QCoreSettings ( QObject * parent = 0 )

Constructs a QCoreSettings object for accessing settings of the application and organization set previously with a call to QCoreApplication::setProductInfo().

The scope is Qt::UserScope and the format is Qt::NativeFormat.

The code

        QCoreSettings settings("www.technopro.co.jp", "Facturo-Pro");

is equivalent to

        qApp->setProductInfo("www.technopro.co.jp", "Facturo-Pro");
        QCoreSettings settings;

If QApplication::setProductInfo() has not been previously called, the QCoreSettings object will not be able to read or write any settings, and status() will return `AccessError`.

### QCoreSettings::~QCoreSettings ()

Destroys the QCoreSettings object. Any unsaved changes will be written to permanent storage at that point.

See also sync().

### QStringList QCoreSettings::allKeys () const

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

Example:

        QCoreSettings settings;
        settings.setValue("fridge/color", 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:

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

See also childGroups() and childKeys().

### void QCoreSettings::beginGroup ( const QString & prefix )

Appends prefix to the current group.

The current group is automatically prepended to all keys specified to QCoreSettings. 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("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 beginGroup() call. Groups can be nested.

See also endGroup() and group().

### int QCoreSettings::beginReadArray ( const QString & prefix )

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

Example:

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

        QCoreSettings settings;
        int size = settings.beginReadArray("logins");
        for (int i = 0; i < size; ++i) {
            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 beginWriteArray(), endArray(), and setArrayIndex().

### void QCoreSettings::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 variable-length list of user names and passwords. You could then write:

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

        QCoreSettings settings;
        settings.beginWriteArray("logins");
        for (int i = 0; i < logins.size(); ++i) {
            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/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 beginReadArray(), endArray(), and setArrayIndex().

### QStringList QCoreSettings::childGroups () const

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

Example:

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

        QStringList 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 childGroups() recursively.

See also childKeys() and allKeys().

### QStringList QCoreSettings::childKeys () const

Returns a list of all top-level keys that can be read using the QCoreSettings object.

Example:

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

        QStringList 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 childKeys() and childGroups() recursively.

See also childGroups() and allKeys().

### void QCoreSettings::clear ()

Removes all entries in the primary location associated to this QCoreSettings object.

Entries in fallback locations are not removed.

See also remove() and setFallbacksEnabled().

### bool QCoreSettings::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().

### void QCoreSettings::endArray ()

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

See also beginReadArray() and beginWriteArray().

### void QCoreSettings::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 beginGroup() and group().

### bool QCoreSettings::fallbacksEnabled () const

Returns true if fallbacks are enabled; returns false otherwise.

By default, fallbacks are enabled.

See also setFallbacksEnabled() and Fallback Mechanism.

### QString QCoreSettings::fileName () const

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

On Windows, if format() is Qt::NativeFormat, the return value is a system registry path, not a file path.

See also isWritable().

### QString QCoreSettings::group () const

Returns the current group.

See also beginGroup() and endGroup().

### bool QCoreSettings::isWritable () const

Returns true if settings can be written using this QCoreSettings object; returns false otherwise.

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

See also fileName() and status().

### void QCoreSettings::remove ( const QString & key )

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

Example:

        QCoreSettings settings;
        settings.setValue("ape");
        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().

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

### void QCoreSettings::setArrayIndex ( int i )

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

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

### void QCoreSettings::setFallbacksEnabled ( bool b )

Sets whether fallbacks are enabled to b.

By default, fallbacks are enabled.

See also fallbacksEnabled() and Fallback Mechanism.

### void QCoreSettings::setValue ( const QString & key, const QCoreVariant & value )

Sets the value of setting key to value.

If the key already exists, the previous value is overwritten.

Example:

        QCoreSettings settings;
        settings.setValue("interval", 30);
        settings.value("interval").toInt();     // returns 30

        settings.setValue("interval", 6.55);
        settings.value("interval").toDouble();  // returns 6.55

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

### Status QCoreSettings::status () const

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

### void QCoreSettings::sync ()

Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application.

Unless you use QCoreSettings as a communication mechanism between different processes, you normally don't need to call this function.

### QCoreVariant QCoreSettings::value ( const QString & key, const QCoreVariant & defaultValue = QCoreVariant() ) const

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

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

Example:

        QCoreSettings settings;
        settings.setValue("snake", 58);
        settings.value("snake", 1024).toInt();  // returns 58
        settings.value("zebra", 1024).toInt();  // returns 1024
        settings.value("zebra").toInt();        // returns 0

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