QSettings Class▲
-
Header: QSettings
-
CMake:
find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
-
qmake: QT += core
-
Inherits: QObject
-
Group: QSettings is part of Input/Output and Networking
Detailed Description▲
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on macOS and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.
QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports custom storage formats.
QSettings's API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort.
If all you need is a non-persistent memory-based structure, consider using QMap<QString, QVariant> instead.
Basic Usage▲
When creating a QSettings object, you must pass the name of your company or organization as well as the name of your application. For example, if your product is called Star Runner and your company is called MySoft, you would construct the QSettings object as follows:
QSettings settings("MySoft"
, "Star Runner"
);
QSettings objects can be created either on the stack or on the heap (i.e. using new). 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("MySoft"
);
QCoreApplication::
setOrganizationDomain("mysoft.com"
);
QCoreApplication::
setApplicationName("Star Runner"
);
...
QSettings settings;
(Here, we also specify the organization's Internet domain. When the Internet domain is set, it is used on macOS and iOS instead of the organization name, since macOS and iOS applications conventionally use Internet domains to identify themselves. If no domain is set, a fake domain is derived from the organization name. See the Platform-Specific Notes below for details.)
QSettings stores settings. Each setting consists of a QString that specifies the setting's name (the key) and a QVariant that stores the data associated with the key. To write a setting, use setValue(). For example:
settings.setValue("editor/wrapMargin"
, 68
);
If there already exists a setting with the same key, the existing value is overwritten by the new value. For efficiency, the changes may not be saved to permanent storage immediately. (You can always call sync() to commit your changes.)
You can get a setting's value back using value():
int
margin =
settings.value("editor/wrapMargin"
).toInt();
If there is no setting with the specified name, QSettings returns a null QVariant (which can be converted to the integer 0). You can specify another default value by passing a second argument to value():
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▲
Because QVariant is part of the Qt Core module, it cannot provide conversion functions to data types such as QColor, QImage, and QPixmap, which are part of Qt GUI. In other words, there is no toColor(), toImage(), or toPixmap() functions in QVariant.
Instead, you can use the QVariant::value() template function. For example:
QSettings settings("MySoft"
, "Star Runner"
);
QColor color =
settings.value("DataPump/bgcolor"
).value&
lt;QColor&
gt;();
The inverse conversion (e.g., from QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types:
QSettings settings("MySoft"
, "Star Runner"
);
QColor color =
palette().background().color();
settings.setValue("DataPump/bgcolor"
, color);
Custom types registered using qRegisterMetaType() that have operators for streaming to and from a QDataStream can be stored using QSettings.
Section and Key Syntax▲
Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, follow these simple rules:
-
Always refer to the same key using the same case. For example, if you refer to a key as "text fonts" in one place in your code, don't refer to it as "Text Fonts" somewhere else.
-
Avoid key names that are identical except for the case. For example, if you have a key called "MainWindow", don't try to save another key as "mainwindow".
-
Do not use slashes ('/' and '\') in section or key names; the backslash character is used to separate sub keys (see below). On windows '\' are converted by QSettings to '/', which makes them identical.
You can form hierarchical keys using the '/' character as a separator, similar to Unix file paths. For example:
settings.setValue("mainwindow/size"
, win-&
gt;size());
settings.setValue("mainwindow/fullScreen"
, win-&
gt;isFullScreen());
settings.setValue("outputpanel/visible"
, panel-&
gt;isVisible());
If you want to save or restore 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-&
gt;size());
settings.setValue("fullScreen"
, win-&
gt;isFullScreen());
settings.endGroup();
settings.beginGroup("outputpanel"
);
settings.setValue("visible"
, panel-&
gt;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.
Fallback Mechanism▲
Let's assume that you have created a QSettings object with the organization name MySoft and the application name Star Runner. When you look up a value, up to four locations are searched in that order:
-
a user-specific location for the Star Runner application
-
a user-specific location for all applications by MySoft
-
a system-wide location for the Star Runner application
-
a system-wide location for all applications by MySoft
(See Platform-Specific Notes below for information on what these locations are on the different platforms supported by Qt.)
If a key cannot be found in the first location, the search goes on in the second location, and so on. This enables you to store system-wide or organization-wide settings and to override them on a per-user or per-application basis. To turn off this mechanism, call setFallbacksEnabled(false).
Although keys from all four locations are available for reading, only the first file (the user-specific location for the application at hand) is accessible for writing. To write to any of the other files, omit the application name and/or specify QSettings::SystemScope (as opposed to QSettings::UserScope, the default).
Let's see with an example:
QSettings obj1("MySoft"
, "Star Runner"
);
QSettings obj2("MySoft"
);
QSettings obj3(QSettings::
SystemScope, "MySoft"
, "Star Runner"
);
QSettings obj4(QSettings::
SystemScope, "MySoft"
);
The table below summarizes which QSettings objects access which location. "X" means that the location is the main location associated to the QSettings object and is used both for reading and for writing; "o" means that the location is used as a fallback when reading.
Locations |
obj1 |
obj2 |
obj3 |
obj4 |
---|---|---|---|---|
1. User, Application |
X |
|||
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 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,
"MySoft"
, "Star Runner"
);
Note that INI files lose the distinction between numeric data and the strings used to encode them, so values written as numbers shall be read back as QString. The numeric value can be recovered using QString::toInt(), QString::toDouble() and related functions.
The Settings Editor example lets you experiment with different settings location and with fallbacks turned on or off.
Restoring the State of a GUI Application▲
QSettings is often used to store the state of a GUI application. The following example illustrates how to use QSettings to save and restore the geometry of an application's main window.
void
MainWindow::
writeSettings()
{
QSettings settings("Moose Soft"
, "Clipper"
);
settings.beginGroup("MainWindow"
);
settings.setValue("geometry"
, saveGeometry());
settings.endGroup();
}
void
MainWindow::
readSettings()
{
QSettings settings("Moose Soft"
, "Clipper"
);
settings.beginGroup("MainWindow"
);
const
auto
geometry =
settings.value("geometry"
, QByteArray()).toByteArray();
if
(geometry.isEmpty())
setGeometry(200
, 200
, 400
, 400
);
else
restoreGeometry(geometry)
settings.endGroup();
}
See Window Geometry for a discussion on why it is better to call QWidget::resize() and QWidget::move() rather than QWidget::setGeometry() to restore a window's geometry.
The readSettings() and writeSettings() functions must be called from the main window's constructor and close event handler as follows:
MainWindow::
MainWindow()
{
...
readSettings();
}
void
MainWindow::
closeEvent(QCloseEvent *
event)
{
if
(userReallyWantsToQuit()) {
writeSettings();
event-&
gt;accept();
}
else
{
event-&
gt;ignore();
}
}
See the Application example for a self-contained example that uses QSettings.
Accessing Settings from Multiple Threads or Processes Simultaneously▲
QSettings is reentrant. This means that you can use 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, provided certain conditions are met. For QSettings::IniFormat, it uses advisory file locking and a smart merging algorithm to ensure data integrity. The condition for that to work is that the writeable configuration file must be a regular file and must reside in a directory that the current user can create new, temporary files in. If that is not the case, then one must use setAtomicSyncRequired() to turn the safety off.
Note that sync() imports changes made by other processes (in addition to writing the changes from this QSettings).
Platform-Specific Notes▲
Locations Where Application Settings Are Stored▲
As mentioned in the Fallback Mechanism section, QSettings stores settings for an application in up to four locations, depending on whether the settings are user-specific or system-wide and whether the settings are application-specific or organization-wide. For simplicity, we're assuming the organization is called MySoft and the application is called Star Runner.
On Unix systems, if the file format is NativeFormat, the following files are used by default:
-
$HOME/.config/MySoft/Star Runner.conf
-
$HOME/.config/MySoft.conf
-
for each directory <dir> in $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.conf
-
for each directory <dir> in $XDG_CONFIG_DIRS: <dir>/MySoft.conf
If XDG_CONFIG_DIRS is unset, the default value of /etc/xdg is used.
On macOS and iOS, if the file format is NativeFormat, these files are used by default:
-
$HOME/Library/Preferences/com.MySoft.Star Runner.plist
-
$HOME/Library/Preferences/com.MySoft.plist
-
/Library/Preferences/com.MySoft.Star Runner.plist
-
/Library/Preferences/com.MySoft.plist
On Windows, NativeFormat settings are stored in the following registry paths:
-
HKEY_CURRENT_USER\Software\MySoft\Star Runner
-
HKEY_CURRENT_USER\Software\MySoft\OrganizationDefaults
-
HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
-
HKEY_LOCAL_MACHINE\Software\MySoft\OrganizationDefaults
On Windows, for 32-bit programs running in WOW64 mode, settings are stored in the following registry path: HKEY_LOCAL_MACHINE\Software\WOW6432node.
If the file format is NativeFormat, this is "Settings/MySoft/Star Runner.conf" in the application's home directory.
If the file format is IniFormat, the following files are used on Unix, macOS, and iOS:
-
$HOME/.config/MySoft/Star Runner.ini
-
$HOME/.config/MySoft.ini
-
for each directory <dir> in $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.ini
-
for each directory <dir> in $XDG_CONFIG_DIRS: <dir>/MySoft.ini
If XDG_CONFIG_DIRS is unset, the default value of /etc/xdg is used.
On Windows, the following files are used:
-
FOLDERID_RoamingAppData\MySoft\Star Runner.ini
-
FOLDERID_RoamingAppData\MySoft.ini
-
FOLDERID_ProgramData\MySoft\Star Runner.ini
-
FOLDERID_ProgramData\MySoft.ini
The identifiers prefixed by FOLDERID_ are special item ID lists to be passed to the Win32 API function SHGetKnownFolderPath() to obtain the corresponding path.
FOLDERID_RoamingAppData usually points to C:\Users\User Name\AppData\Roaming, also shown by the environment variable %APPDATA%.
FOLDERID_ProgramData usually points to C:\ProgramData.
If the file format is IniFormat, this is "Settings/MySoft/Star Runner.ini" in the application's home directory.
The paths for the .ini and .conf files can be changed using setPath(). On Unix, macOS, and iOS the user can override them by setting the XDG_CONFIG_HOME environment variable; see setPath() for details.
Accessing INI and .plist Files Directly▲
Sometimes you do want to access settings stored in a specific file or registry path. On all platforms, if you want to read an INI file directly, you can use the QSettings constructor that takes a file name as first argument and pass QSettings::IniFormat as second argument. For example:
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 macOS and iOS, you can access property list .plist files by passing QSettings::NativeFormat as second argument. For example:
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.
For example:
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). For example:
settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles"
, 0
);
Note that the backslash character is, as mentioned, used by QSettings to separate subkeys. As a result, you cannot read or write windows registry entries that contain slashes or backslashes; you should use a native windows API if you need to do so.
Accessing Common Registry Settings on Windows▲
On Windows, it is possible for a key to have both a value and subkeys. Its default value is accessed by using "Default" or "." in place of a subkey:
settings.setValue("HKEY_CURRENT_USER
\\
MySoft
\\
Star Runner
\\
Galaxy"
, "Milkyway"
);
settings.setValue("HKEY_CURRENT_USER
\\
MySoft
\\
Star Runner
\\
Galaxy
\\
Sun"
, "OurStar"
);
settings.value("HKEY_CURRENT_USER
\\
MySoft
\\
Star Runner
\\
Galaxy
\\
Default"
); // returns "Milkyway"
On other platforms than Windows, "Default" and "." would be treated as regular subkeys.
Platform Limitations▲
While QSettings attempts to smooth over the differences between the different supported platforms, there are still a few differences that you should be aware of when porting your application:
-
The Windows system registry has the following limitations: A subkey may not exceed 255 characters, an entry's value may not exceed 16,383 characters, and all the values of a key may not exceed 65,535 characters. One way to work around these limitations is to store the settings using the IniFormat instead of the NativeFormat.
-
On Windows, when the Windows system registry is used, QSettings does not preserve the original type of the value. Therefore, the type of the value might change when a new value is set. For exam