CopperSpice API  1.9.1
QSettings Class Reference

The QSettings class provides a way to save and restore user or application settings. More...

Inheritance diagram for QSettings:
QObject

Public Typedefs

using ReadFunc = bool (*)(QIODevice &device, SettingsMap &map)
 
using SettingsMap = QMap< QString, QVariant >
 
using WriteFunc = bool (*)(QIODevice &device, const SettingsMap &map)
 

Public Types

enum  Format
 
enum  Scope
 
enum  Status
 

Public Methods

 QSettings (const QString &fileName, Format format, QObject *parent=nullptr)
 
 QSettings (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 (QObject *parent=nullptr)
 
 QSettings (Scope scope, const QString &organization, const QString &application=QString (), QObject *parent=nullptr)
 
 ~QSettings ()
 
QStringList allKeys () const
 
QString applicationName () 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
 
Format format () const
 
QString group () const
 
QTextCodeciniCodec () const
 
bool isWritable () const
 
QString organizationName () const
 
void remove (const QString &key)
 
Scope scope () const
 
void setArrayIndex (int i)
 
void setFallbacksEnabled (bool b)
 
void setIniCodec (const char *codecName)
 
void setIniCodec (QTextCodec *codec)
 
void setValue (const QString &key, const QVariant &value)
 
Status status () const
 
void sync ()
 
QVariant value (const QString &key, const QVariant &defaultValue=QVariant ()) const
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &childName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Static Public Methods

static Format defaultFormat ()
 
static Format registerFormat (const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity=Qt::CaseSensitive)
 
static void setDefaultFormat (Format format)
 
static void setPath (Format format, Scope scope, const QString &path)
 
static void setSystemIniPath (const QString &dir)
 
static void setUserIniPath (const QString &dir)
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 

Protected Methods

bool event (QEvent *event) override
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 

Additional Inherited Members

- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 
- Public Slots inherited from QObject
void deleteLater ()
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QSettings class provides a way to save and restore user or application settings from one run to another. It is very common for an application to retain prior settings when the program is started. For example, the application window size, position, or a list of files which were opened the last time the application was closed.

The settings often typically stored in the system registry on Windows. On Unix and Mac OS X the settings are saved in a file in the users home directory. QSettings supports custom storage formats.

Most data types which can be converted to a QVariant can be saved using the QSettings class. This includes types like a QString, QRect, and QImage.

Basic Usage

When creating a QSettings object one of the most common overloads to use involves passing the name of your company or organization and the name of the application. For example, if your organization is called "Corvallis Management" and the application is called "Inventory Application", construct the QSettings object as shown below.

QSettings settings("Corvallis Management", "Inventory Application");

Constructing and destroying a QSettings object is very fast.

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

QCoreApplication::setOrganizationName("Corvallis Management");
QCoreApplication::setOrganizationDomain("corvallis-management.com");
QCoreApplication::setApplicationName("Inventory Application");
QSettings settings;

In this code we specified the organization's Internet domain. On Mac OS X if an Internet domain is set it will be used in place of the organization name to conform to their conventions. If no domain is set, a fake domain is derived from the organization name.

Refer to the Platform Specific Notes for more details.

Saving a Value

To save a setting use setValue() and pass a key and a value. If the key previously existed the old value will be overwritten with the new value. For efficiency the changes may not be saved to permanent storage immediately. Call sync() to commit the changes right away.

settings.setValue("editor/wrapMargin", 68);

To retrieve the value call the value() method. If there is no setting with the specified key QSettings will return an invalid QVariant.

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

To ensure a value is retrieved, in the case that the key was not found, pass a second argument to value() as shown in the following example.

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

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

QVariant and GUI Types

The QVariant class is part of the CsCore library and can not provide conversion functions to data types such as QColor, QImage, and QPixmap, which are part of CsGui. There are no toColor(), toImage(), or toPixmap() functions in QVariant. Instead use the QVariant::value() method.

QSettings settings("Corvallis Management", "Inventory Application");
QColor color = settings.value("fridge/color").value<QColor>();

The reverse operation, from QColor to QVariant is automatic for all data types supported by QVariant, including GUI related types.

QSettings settings("Corvallis Management", "Inventory Application");
QColor color = palette().background().color();
settings.setValue("fridge/color", color);

Section 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 issues follow these 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, do not refer to it as "Text Fonts" somewhere else.

  2. Avoid key names that are identical except for the case.
    For example, if you have a key called "mainwindow", do not try to save another key as "mainwindow".

  3. Do not use a forward slash or back slash in section or key names since the backslash character is used to separate sub keys.
    On windows '\' is converted by QSettings to '/', which makes them identical.

You can form hierarchical keys using the '/' character as a separator, similar to Unix file paths.

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 several settings with the same prefix, specify the prefix using beginGroup() and call endGroup() at the end. Here is the same example using the group mechanism.

settings.beginGroup("mainwindow");
settings.setValue("size", win->size());
settings.setValue("fullScreen", win->isFullScreen());
settings.endGroup();
settings.beginGroup("outputpanel");
settings.setValue("visible", panel->isVisible());
settings.endGroup();

If a group is set using beginGroup(), the behavior of most functions changes consequently. Groups can be set recursively. In addition to groups, QSettings also supports an "array" concept. See beginReadArray() and beginWriteArray() for details.

Platform Storage Locations

The QSettings keys and values will be stored in one of four different files or locations based on how the constructor was called and the target platform.

  • user settings location for Inventory Application
  • user settings location for all applications by Corvallis Management
  • global settings location for Inventory Application
  • global settings location for all applications by Corvallis Management

Format of QSettings::NativeFormat

Unix
  1. $HOME/.config/Corvallis Management/Inventory Application.conf
  2. $HOME/.config/Corvallis Management.conf
  3. /etc/xdg/Corvallis Management/Inventory Application.conf
  4. /etc/xdg/Corvallis Management.conf
Mac OS X
  1. $HOME/Library/Preferences/com.Corvallis Management.Inventory Application.plist
  2. $HOME/Library/Preferences/com.Corvallis Management.plist
  3. /Library/Preferences/com.Corvallis Management.Inventory Application.plist
  4. /Library/Preferences/com.Corvallis Management.plist
Windows, registry paths
  1. HKEY_CURRENT_USER\Software\Corvallis Management\Inventory Application
  2. HKEY_CURRENT_USER\Software\Corvallis Management
  3. HKEY_LOCAL_MACHINE\Software\Corvallis Management\Inventory Application
  4. HKEY_LOCAL_MACHINE\Software\Corvallis Management

On Windows 32-bit programs running in WOW64 mode settings are stored in the following registry path: HKEY_LOCAL_MACHINE\Software\WOW6432node.

Format of QSettings::IniFormat

Unix and Mac OS X
  1. $HOME/.config/Corvallis Management/Inventory Application.ini
  2. $HOME/.config/Corvallis Management.ini
  3. /etc/xdg/Corvallis Management/Inventory Application.ini
  4. /etc/xdg/Corvallis Management.ini
Windows
  1. %APPDATA%\Corvallis Management\Inventory Application.ini
  2. %APPDATA%\Corvallis Management.ini
  3. %COMMON_APPDATA%\Corvallis Management\Inventory Application.ini
  4. %COMMON_APPDATA%\Corvallis Management.ini

The %APPDATA% path is usually "C:\Documents and Settings\User Name\Application Data" and 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 setPath(). On Unix and Mac OS X, the user can override them by setting the XDG_CONFIG_HOME environment variable. Refer to setPath() for details.

Order of Searching

If a key can not be found in the first location the search goes on in the second location, and so on. This enables storing user and global 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 user specific locations for the given application are accessible for writing. To write to any of the other settings omit the application name or specify QSettings::SystemScope as opposed to QSettings::UserScope.

QSettings obj1("Corvallis Management", "Inventory Application");
QSettings obj2("Corvallis Management");
QSettings obj3(QSettings::SystemScope, "Corvallis Management", "Inventory Application");
QSettings obj4(QSettings::SystemScope, "Corvallis Management");

The table below summarizes which QSettings objects access which location. The "X" means that the location is the primary location associated with the QSettings object and is used to read and write, where as "o" indicates the location is used as a fallback when reading.

Locationsobj1obj2obj3obj4
1.  User ApplicationX
2.  User OrganizationoX
3.  Global ApplicationoX
4.  Global OrganizationoooX

To use INI files on all platforms instead of the native API, pass QSettings::IniFormat as the first argument to the QSettings constructor, followed by the scope, the organization name, and the application name.

QSettings settings(QSettings::IniFormat, QSettings::UserScope, "Corvallis Management", "Inventory Application);

Restoring the State of a GUI Application

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

void MainWindow::writeSettings()
{
QSettings settings("Corvallis Management", "Inventory Application");
settings.beginGroup("MainWindow");
settings.setValue("size", size());
settings.setValue("pos", pos());
settings.endGroup();
}
void MainWindow::readSettings()
{
QSettings settings("Corvallis Management", "Inventory Application");
settings.beginGroup("MainWindow");
resize(settings.value("size", QSize(400, 400)).toSize());
move(settings.value("pos", QPoint(200, 200)).toPoint());
settings.endGroup();
}

Refer to 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:

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

Accessing INI and .plist Files Directly

Sometimes you do want to access settings stored in a specific file or registry path. On all platforms, if you want to read an INI file directly, you can use the QSettings constructor that takes a file name as first argument and pass QSettings::IniFormat as second argument.

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

You can then use the 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.

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

Accessing the Windows Registry Directly

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

QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office", QSettings::NativeFormat);

All the registry entries that appear under the specified path can be read or written through the QSettings object as usual (using forward slashes instead of backslashes).

settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0);

The backslash character is used by QSettings to separate subkeys. As a result, you can not 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\\Corvallis\\Star Runner\\Galaxy", "Milkyway");
settings.setValue("HKEY_CURRENT_USER\\Corvallis\\Star Runner\\Galaxy\\Sun", "OurStar");
settings.value("HKEY_CURRENT_USER\\Corvallis\\Star Runner\\Galaxy\\Default"); // returns "Milkyway"

On other platforms than Windows, "Default" and "." would be treated as regular subkeys.

Location of global settings on Mac OS X

On Mac OS X the global CopperSpice settings (in com.copperspice.plist) are stored in the application settings file in two situations.

  1. If the application runs in a Mac OS X sandbox or
  2. If the Info.plist file of the application contains the key "ForAppStore" with the value "yes"

In these situations the application settings file is named using the bundle identifier of the application, which must consequently be set in the application's Info.plist file.

This feature is provided to ease the acceptance of CopperSpice applications into the App Store, as the default behavior of storing global CopperSpice settings in the com.copperspice.plist file does not conform with App Store file system usage requirements. For more information about submitting applications to the App Store, refer to the Apple on line documentation.

Platform Limitations

While QSettings attempts to smooth over the differences between the different supported platforms, there are still a few which developers need to be aware of.

  • The Windows system registry has some limitations. A subkey may not exceed 255 characters, an value for an entry can 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 the allKeys() method can return extra global keys which apply to all applications. The extra keys can be read using value() however they can not be changed. If you add a key to your application with the same name as a global key they global value will be hidden. Calling setFallbacksEnabled(false) is the way to hide global settings.
  • On Mac OS X the CFPreferences API used by QSettings expects Internet domain names rather than organization names. To provide a uniform API, QSettings derives a fake domain name from the organization name (unless the organization name already is a domain name, e.g. OpenOffice.org). The algorithm appends ".com" to the company name and replaces spaces and other illegal characters with hyphens. If you want to specify a different domain name, call QCoreApplication::setOrganizationDomain(), QCoreApplication::setOrganizationName(), and QCoreApplication::setApplicationName() in your main() function and then use the default QSettings constructor. Another solution is to use preprocessor directives as shown in the following code.

    #ifdef Q_OS_DARWIN
    QSettings settings("grenoullelogique.fr", "Squash");
    #else
    QSettings settings("Grenoulle Logique", "Squash");
    #endif
  • On Unix and Mac OS X the file locking is disabled if NFS (or AutoFS or CacheFS) is detected to work around an issue in the NFS fcntl() implementation, which hangs forever if statd or lockd are not running. Also, the locking is not performed when accessing .plist files.

Accessing Settings from Multiple Threads or Processes Simultaneously

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

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

See also
QVariant, QSessionManager

Member Typedef Documentation

Typedef for a pointer to a call back function.

The data type of ReadFunc is passed to registerFormat() as a pointer to a user defined call back which reads a set of (key, value) pairs. The call back function should read all the options and return the settings in the SettingsMap container which is initially empty.

The following is the signature for the call back function.

bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map);
See also
WriteFunc, registerFormat()

Typedef for a pointer to a call back function.

The data type of WriteFunc is passed to registerFormat() as a pointer to a user defined call back which writes a set of (key, value) pairs. The call back function should write all the options in the settings in the SettingsMap container.

The following is the signature for the call back function.

bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map);
See also
ReadFunc, registerFormat()

Member Enumeration Documentation

This enum type specifies the storage format used by QSettings.

ConstantValueDescription
QSettings::NativeFormat0 Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry. For Mac OS X this means the CFPreferences API, on Unix this means textual configuration files in INI format.
QSettings::IniFormat1Store the settings in INI files.
QSettings::InvalidFormat16Special value returned by registerFormat().

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

File Format

The INI file format is a Windows file format which is supported on all platforms. In the absence of an INI standard we follow the Microsoft guidelines with the following exceptions.

  • If you store types that QVariant can not convert to QString (like QPoint, QRect, or QSize), QSettings adds an '@' followed by the data type. To minimize compatibility issues any '@' which does not appear at the first position in the value or is not followed by a data type name is treated as a normal character.

    pos = @Point(100 100)
  • Although backslash is a special character in INI files most Windows applications do not escape backslashes in the file path. QSettings always treats backslash as a special character and provides no API for reading or writing such entries.

    windir = c:\Windows\System
  • The INI file format has severe restrictions on the syntax of a key. CopperSpice 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 such as "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, and not in the "General" section.

  • Following the philosophy that we should be liberal in what we accept and conservative in what we generate, QSettings will accept Latin-1 encoded INI files, but generate pure ASCII files, where non-ASCII values are encoded using standard INI escape sequences. To make the INI files more readable (but potentially less compatible), call setIniCodec().
See also
registerFormat(), setPath()

This enum specifies whether settings are user-specific or shared by all users of the same system.

ConstantValueDescription
QSettings::UserScope0 Store settings in a location specific to the current user (e.g., in the user's home directory).
QSettings::SystemScope1 Store settings in a global location, so that all users on the same machine access the same set of settings.
See also
setPath()

The following status values are possible:

ConstantValueDescription
QSettings::NoError0 No error occurred.
QSettings::AccessError1 An access error occurred (e.g. trying to write to a read only file).
QSettings::FormatError2 A format error occurred (e.g. loading a malformed INI file).
See also
status()

Constructor & Destructor Documentation

QSettings::QSettings ( const QString organization,
const QString application = QString(),
QObject parent = nullptr 
)
explicit

Constructs a QSettings object using the given organization, application, and parent. If no application name is specified the QSettings object will only access settings for the organization which have a empty application property.

The scope is set to QSettings::UserScope and the format is set to QSettings::NativeFormat. Calling setDefaultFormat() before calling this constructor will have no effect.

QSettings settings("Corvallis Management", "Inventory Application");
See also
setDefaultFormat()
QSettings::QSettings ( Scope  scope,
const QString organization,
const QString application = QString(),
QObject parent = nullptr 
)

Constructs a QSettings object using the given scope, organization, application, and parent. If no application name is specified the QSettings object will only access settings for the organization which have a empty application property.

If the scope is QSettings::UserScope the QSettings object searches user specific settings first, before it searches the global settings. If scope is QSettings::SystemScope, the QSettings object ignores user specific settings and provides access to the global settings.

The storage format is automatically set to QSettings::NativeFormat. Calling setDefaultFormat() before calling this constructor will have no effect.

See also
setDefaultFormat()
QSettings::QSettings ( Format  format,
Scope  scope,
const QString organization,
const QString application = QString(),
QObject parent = nullptr 
)

Constructs a QSettings object using the given format, scope, organization, application, and parent. If no application name is specified the QSettings object will only access settings for the organization which have a empty application property.

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

If the scope is QSettings::UserScope the QSettings object searches user specific settings first, before it searches the global settings. If scope is QSettings::SystemScope, the QSettings object ignores user specific settings and provides access to the global settings.

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

Constructs a QSettings object using the given fileName, format, and parent. If the file does not exist it is created automatically. The file name is relative to the current working directory. Even if a path is set using QSettings::setPath() it will not be prepended to the file name.

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

If the value of format is QSettings::IniFormat the given fileName is the name of an INI file.

// example 1 - path is relative to the current dir, file name is "TestSettings.ini"
QSettings data1("TestSettings.ini", QSettings::IniFormat);
// example 2 - path is targetLocation, file name is "CopperSpice.ini"
QString targetLocation = QDir::tempPath();
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, targetLocation);
QSettings data2(QSettings::IniFormat, QSettings::UserScope, "CopperSpice");

Limitations

The method works well for reading INI or *.plist files which were created by CopperSpice applications. When reading a file which was written by a non CopperSpice application, the following limitations may apply.

  • QSettings can not read an entry where the key contains unescaped slash characters.
  • Values which contain an @ character may be read incorrectly
See also
fileName()
QSettings::QSettings ( QObject parent = nullptr)
explicit

Constructs a 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 defaultFormat() (QSettings::NativeFormat by default). Use setDefaultFormat() before calling this constructor to change the default format used by this constructor.

The following code,

QSettings settings("Corvallis Management", "Inventory Application");

is equivalent to,

QCoreApplication::setOrganizationName("Corvallis Management");
QCoreApplication::setApplicationName("Inventory Application");
QSettings settings;

On Windows, if QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName() were not previously set, the QSettings object will be unable to read or write any settings and the status() method will return QSettings::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.

See also
QCoreApplication::setOrganizationName(), QCoreApplication::setOrganizationDomain(), QCoreApplication::setApplicationName(), setDefaultFormat()
QSettings::~QSettings ( )

Destroys the QSettings object. Any unsaved changes will eventually be written to permanent storage.

See also
sync()

Method Documentation

QStringList QSettings::allKeys ( ) const

Returns a list of all the keys including any subkeys, which were previously stored by the QSettings object. This method can return additional keys other than those which belong to the specified organization and application.

windows notation: if the application is not passed the keys will be added to OrganizationDefaults

Refer to Platform Storage Locations for more information.

QSettings settings("Corvallis Management", "Inventory Application");
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(), childKeys()
QString QSettings::applicationName ( ) const

Returns the application name used for storing the settings.

See also
QCoreApplication::applicationName(), format(), scope(), organizationName()
void QSettings::beginGroup ( const QString prefix)

Appends prefix to the current group. Groups are useful to avoid typing in the same setting paths over and over.

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.

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();

The following will set the value for these 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(), 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.

struct Login {
QString userName;
QString password;
};
QList<Login> logins;
...
QSettings settings;
int size = settings.beginReadArray("logins");
for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
Login login;
login.userName = settings.value("userName").toString();
login.password = settings.value("password").toString();
logins.append(login);
}
settings.endArray();

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

See also
beginWriteArray(), endArray(), setArrayIndex()
void QSettings::beginWriteArray ( const QString prefix,
int  size = -1 
)

Adds prefix to the current group and starts writing an array of 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 us 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;
...
QSettings 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/size
  • logins/1/userName
  • logins/1/password
  • logins/2/userName
  • logins/2/password
  • logins/3/userName
  • logins/3/password
  • ...

To read back an array, use beginReadArray().

See also
beginReadArray(), endArray(), 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.

QSettings 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();
// groups: ["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(), allKeys()
QStringList QSettings::childKeys ( ) const

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

QSettings 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(), allKeys()
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(), setFallbacksEnabled()
bool QSettings::contains ( const QString key) const

Returns true if there exists a setting called key, otherwise returns false. If a group is set using beginGroup() then the key is taken to be relative to that group. 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 refer to the Section and Key Syntax rules.

See also
value(), setValue()
Format QSettings::defaultFormat ( )
static

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

See also
setDefaultFormat(), format()
void QSettings::endArray ( )

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

See also
beginReadArray(), beginWriteArray()
void QSettings::endGroup ( )

Resets the group to what it was before the corresponding beginGroup() call.

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(), group()
bool QSettings::event ( QEvent event)
overrideprotectedvirtual

Reimplemented from QObject::event()

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. On Windows, if the format is QSettings::NativeFormat, the return value is a system registry path, not a file path.

See also
isWritable(), format()
Format QSettings::format ( ) const

Returns the format used for storing the settings.

See also
defaultFormat(), fileName(), scope(), organizationName(), applicationName()
QString QSettings::group ( ) const

Returns the current group.

See also
beginGroup(), endGroup()
QTextCodec * QSettings::iniCodec ( ) const

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

See also
setIniCodec()
bool QSettings::isWritable ( ) const

Returns true if settings can be written using this QSettings object; returns false otherwise. One reason why isWritable() might return false is if QSettings operates on a read only file.

This method is not guaranteed since file permissions can change at any time.

See also
fileName(), status(), sync()
QString QSettings::organizationName ( ) const

Returns the organization name used for storing the settings.

See also
QCoreApplication::organizationName(), format(), scope(), applicationName()
Format QSettings::registerFormat ( const QString extension,
ReadFunc  readFunc,
WriteFunc  writeFunc,
Qt::CaseSensitivity  caseSensitivity = Qt::CaseSensitive 
)
static

Registers a custom storage format. On success this method returns a special Format enum value that can then be passed to the QSettings constructor. On failure it returns QSettings:InvalidFormat.

The extension is the file extension associated to the format without the dot.

The readFunc and writeFunc parameters are pointers to functions which read and write a set of (key, value) pairs. The QIODevice parameter to the read and write functions is always opened in binary mode (for example, without the QIODevice::Text flag).

The caseSensitivity parameter specifies whether keys are case sensitive or not. This makes a difference when looking up values using QSettings. The default is case sensitive.

By default, if you use a QSettings constructor which receives the organization name and an application name, the file system locations will be the same as for IniFormat. Use setPath() to specify other locations.

bool readXmlFile(QIODevice &device, QSettings::SettingsMap &map);
bool writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map);
int main(int argc, char *argv[])
{
const QSettings::Format XmlFormat = QSettings::registerFormat("xml", readXmlFile, writeXmlFile);
QSettings settings(XmlFormat, QSettings::UserScope, "Corvallis", "Star Runner");
}
See also
setPath()
void QSettings::remove ( const QString key)

Removes the setting key and any sub-settings of key. If one of the fallback locations contains a setting with the same key, that setting will be visible after calling remove().

QSettings 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"]

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

QSettings settings;
settings.setValue("ape");
settings.setValue("monkey", 1);
settings.setValue("monkey/sea", 2);
settings.setValue("monkey/doe", 4);
settings.beginGroup("monkey");
settings.remove("");
settings.endGroup();
QStringList keys = settings.allKeys();
// keys: ["ape"]

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 refer to the Section and Key Syntax rules.

See also
setValue(), value(), contains()
Scope QSettings::scope ( ) const

Returns the scope used for storing the settings.

See also
format(), organizationName(), applicationName()
void QSettings::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 QSettings::setDefaultFormat ( Format  format)
static

Sets the default file format to the given format, which is used for storing settings for the QSettings(QObject *) constructor. If no default format is set, QSettings::NativeFormat is used. See the documentation for the QSettings constructor you are using to see if that constructor will ignore this method.

See also
defaultFormat(), format()
void QSettings::setFallbacksEnabled ( bool  b)

Sets whether fallbacks are enabled to b. By default, fallbacks are enabled.

See also
fallbacksEnabled()
void QSettings::setIniCodec ( const char *  codecName)

Sets the codec for accessing INI files (including .conf files on Unix) to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding is not recognized then nothing happens.

See also
QTextCodec::codecForName()
void QSettings::setIniCodec ( QTextCodec codec)

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 QSettings object, before accessing any data.
See also
iniCodec()
void QSettings::setPath ( Format  format,
Scope  scope,
const QString path 
)
static

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.

PlatformFormatScopePath
Windows IniFormat UserScope%APPDATA%
SystemScope%COMMON_APPDATA%
Unix NativeFormat, IniFormat UserScope$HOME/.config
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. Setting the NativeFormat paths on Windows and Mac OS X has no effect.

Note
This method does not affect existing QSettings objects.
See also
registerFormat()
void QSettings::setSystemIniPath ( const QString dir)
deprecatedstatic
Deprecated:
Use setPath() instead.
// prior syntax
// new syntax
setPath(QSettings::NativeFormat, QSettings::SystemScope, path);
setPath(QSettings::IniFormat, QSettings::SystemScope, path);
void QSettings::setUserIniPath ( const QString dir)
deprecatedstatic
Deprecated:
Use setPath() instead.
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.

In 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 refer to the Section and Key Syntax rules.

QSettings 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(), 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.Be aware that QSettings delays performing some operations. For this reason, you might want to call sync() to ensure that the data stored in QSettings is written to disk before calling status().

See also
sync()
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 method is called automatically from the QSettings destructor and by the event loop at regular intervals, so you normally do not need to call it yourself.

See also
status()
QVariant QSettings::value ( const QString key,
const QVariant defaultValue = QVariant() 
) const

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 Windows registry and INI files use case-insensitive keys. On Mac OS X Carbon preferences API uses case-sensitive keys. To avoid portability issues refer to the Section and Key Syntax rules.

QSettings settings;
settings.setValue("animal/snake", 58);
settings.value("animal/snake", 1024).toInt(); // returns 58
settings.value("animal/zebra", 1024).toInt(); // returns 1024
settings.value("animal/zebra").toInt(); // returns 0
See also
setValue(), contains(), remove()