
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQSettings class provides persistent platform-independent application settings.More...
| Header: | #include <QSettings> |
| Inherits: | QObject |
Note: All functions in this class arereentrant, butregisterFormat() is alsothread-safe.
| enum | Format { NativeFormat, IniFormat, InvalidFormat } |
| typedef | ReadFunc |
| enum | Scope { UserScope, SystemScope } |
| typedef | SettingsMap |
| enum | Status { NoError, AccessError, FormatError } |
| typedef | WriteFunc |
| QSettings(const QString & organization, const QString & application = QString(), QObject * parent = 0) | |
| QSettings(Scope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0) | |
| QSettings(Format format, Scope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0) | |
| QSettings(const QString & fileName, Format format, QObject * parent = 0) | |
| QSettings(QObject * parent = 0) | |
| ~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 |
| QTextCodec * | iniCodec() 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(QTextCodec * codec) |
| void | setIniCodec(const char * codecName) |
| void | setValue(const QString & key, const QVariant & value) |
| Status | status() const |
| void | sync() |
| QVariant | value(const QString & key, const QVariant & defaultValue = QVariant()) const |
| Format | defaultFormat() |
| Format | registerFormat(const QString & extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive) |
| void | setDefaultFormat(Format format) |
| void | setPath(Format format, Scope scope, const QString & path) |
| virtual bool | event(QEvent * event) |
TheQSettings class provides persistent platform-independent application settings.
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.
QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supportscustom storage formats.
QSettings's API is based onQVariant, allowing you to save most value-based types, such asQString,QRect, andQImage, with the minimum of effort.
If all you need is a non-persistent memory-based structure, consider usingQMap<QString,QVariant> instead.
When creating aQSettings 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 theQSettings object as follows:
QSettings settings("MySoft","Star Runner");
QSettings objects can be created either on the stack or on the heap (i.e. usingnew). Constructing and destroying aQSettings object is very fast.
If you useQSettings from many places in your application, you might want to specify the organization name and the application name usingQCoreApplication::setOrganizationName() andQCoreApplication::setApplicationName(), and then use the defaultQSettings 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 Mac OS X instead of the organization name, since Mac OS X applications conventionally use Internet domains to identify themselves. If no domain is set, a fake domain is derived from the organization name. See thePlatform-Specific Notes below for details.)
QSettings stores settings. Each setting consists of aQString that specifies the setting's name (thekey) and aQVariant that stores the data associated with the key. To write a setting, usesetValue(). 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 callsync() to commit your changes.)
You can get a setting's value back usingvalue():
int margin= settings.value("editor/wrapMargin").toInt();
If there is no setting with the specified name,QSettings returns a nullQVariant (which can be converted to the integer 0). You can specify another default value by passing a second argument tovalue():
int margin= settings.value("editor/wrapMargin",80).toInt();
To test whether a given key exists, callcontains(). To remove the setting associated with a key, callremove(). To obtain the list of all keys, callallKeys(). To remove all keys, callclear().
BecauseQVariant is part of theQtCore library, it cannot provide conversion functions to data types such asQColor,QImage, andQPixmap, which are part ofQtGui. In other words, there is notoColor(),toImage(), ortoPixmap() functions inQVariant.
Instead, you can use theQVariant::value() or the qVariantValue() template function. For example:
QSettings settings("MySoft","Star Runner");QColor color= settings.value("DataPump/bgcolor").value<QColor>();
The inverse conversion (e.g., fromQColor toQVariant) is automatic for all data types supported byQVariant, including GUI-related types:
QSettings settings("MySoft","Star Runner");QColor color= palette().background().color();settings.setValue("DataPump/bgcolor", color);
Custom types registered usingqRegisterMetaType() andqRegisterMetaTypeStreamOperators() can be stored usingQSettings.
Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, follow these simple rules:
You can form hierarchical keys using the '/' character as a separator, similar to Unix file paths. For example:
settings.setValue("mainwindow/size", win->size()); settings.setValue("mainwindow/fullScreen", win->isFullScreen()); settings.setValue("outputpanel/visible", panel->isVisible());
If you want to save or restore many settings with the same prefix, you can specify the prefix usingbeginGroup() and callendGroup() 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 usingbeginGroup(), the behavior of most functions changes consequently. Groups can be set recursively.
In addition to groups,QSettings also supports an "array" concept. SeebeginReadArray() andbeginWriteArray() for details.
Let's assume that you have created aQSettings 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:
(SeePlatform-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, callsetFallbacksEnabled(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 specifyQSettings::SystemScope (as opposed toQSettings::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 whichQSettings objects access which location. "X" means that the location is the main location associated to theQSettings 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 passQSettings::IniFormat as the first argument to theQSettings constructor, followed by the scope, the organization name, and the application name:
TheSettings Editor example lets you experiment with different settings location and with fallbacks turned on or off.
QSettings is often used to store the state of a GUI application. The following example illustrates how to useQSettings 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("size", size()); settings.setValue("pos", pos()); settings.endGroup();}void MainWindow::readSettings(){QSettings settings("Moose Soft","Clipper"); settings.beginGroup("MainWindow"); resize(settings.value("size",QSize(400,400)).toSize()); move(settings.value("pos",QPoint(200,200)).toPoint()); settings.endGroup();}
SeeWindow Geometry for a discussion on why it is better to callQWidget::resize() andQWidget::move() rather thanQWidget::setGeometry() to restore a window's geometry.
ThereadSettings() andwriteSettings() 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->accept(); }else { event->ignore(); }}
See theApplication example for a self-contained example that usesQSettings.
QSettings isreentrant. This means that you can use distinctQSettings object in different threads simultaneously. This guarantee stands even when theQSettings objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through oneQSettings object, the change will immediately be visible in any otherQSettings 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. Note thatsync() imports changes made by other processes (in addition to writing the changes from thisQSettings).
As mentioned in theFallback 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 isNativeFormat, the following files are used by default:
$HOME/.config/MySoft/Star Runner.conf (Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.conf)$HOME/.config/MySoft.conf (Qt for Embedded Linux:$HOME/Settings/MySoft.conf)/etc/xdg/MySoft/Star Runner.conf/etc/xdg/MySoft.confOn Mac OS X versions 10.2 and 10.3, 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.plistOn Windows,NativeFormat settings are stored in the following registry paths:
HKEY_CURRENT_USER\Software\MySoft\Star RunnerHKEY_CURRENT_USER\Software\MySoftHKEY_LOCAL_MACHINE\Software\MySoft\Star RunnerHKEY_LOCAL_MACHINE\Software\MySoftNote:On Windows, for 32-bit programs running in WOW64 mode, settings are stored in the following registry path:HKEY_LOCAL_MACHINE\Software\WOW6432node.
On BlackBerry only a single file is used (seePlatform Limitations). If the file format isNativeFormat, this is "Settings/MySoft/Star Runner.conf" in the application's home directory.
If the file format isIniFormat, the following files are used on Unix and Mac OS X:
$HOME/.config/MySoft/Star Runner.ini (Qt for Embedded Linux:$HOME/Settings/MySoft/Star Runner.ini)$HOME/.config/MySoft.ini (Qt for Embedded Linux:$HOME/Settings/MySoft.ini)/etc/xdg/MySoft/Star Runner.ini/etc/xdg/MySoft.iniOn Windows, the following files are used:
%APPDATA%\MySoft\Star Runner.ini%APPDATA%\MySoft.ini%COMMON_APPDATA%\MySoft\Star Runner.ini%COMMON_APPDATA%\MySoft.iniThe%APPDATA% path is usuallyC:\Documents and Settings\User Name\Application Data; the%COMMON_APPDATA% path is usuallyC:\Documents and Settings\All Users\Application Data.
On BlackBerry only a single file is used (seePlatform Limitations). If the file format isIniFormat, this is "Settings/MySoft/Star Runner.ini" in the application's home directory.
On Symbian, the following files are used for bothIniFormat andNativeFormat (in this example, we assume that the application is installed on thee-drive and its Secure ID is0xECB00931):
c:\data\.config\MySoft\Star Runner.confc:\data\.config\MySoft.confe:\private\ecb00931\MySoft\Star Runner.confe:\private\ecb00931\MySoft.confTheSystemScope settings location is determined from the installation drive and Secure ID (UID3) of the application. If the application is built-in on the ROM, the drive used forSystemScope isc:.
Note:SymbianSystemScope settings are by default private to the application and not shared between applications, unlike other environments.
The paths for the.ini and.conf files can be changed usingsetPath(). On Unix and Mac OS X, the user can override them by setting theXDG_CONFIG_HOME environment variable; seesetPath() for details.
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 theQSettings constructor that takes a file name as first argument and passQSettings::IniFormat as second argument. For example:
You can then use theQSettings object to read and write settings in the file.
On Mac OS X, you can access XML-based.plist files by passingQSettings::NativeFormat as second argument. For example:
On Windows,QSettings lets you access settings that have been written withQSettings (or settings in a supported format, e.g., string data) in the system registry. This is done by constructing aQSettings object with a path in the registry andQSettings::NativeFormat.
For example:
All the registry entries that appear under the specified path can be read or written through theQSettings 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 byQSettings 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.
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.
UserScope settings in Symbian are writable by any application by default. To protect the application settings from access and tampering by other applications, the settings need to be placed in the private secure area of the application. This can be done by specifying the settings storage path directly to the private area. The following snippet changes theUserScope toc:/private/ecb00931/MySoft.conf (provided the application is installed on thec-drive and its Secure ID is0xECB00931:
QSettings settings(QApplication::applicationDirPath()+"/MySoft.conf");
Framework libraries (like Qt itself) may store configuration and cache settings usingUserScope, which is accessible and writable by other applications. If the application is very security sensitive or uses high platform security capabilities, it may be prudent to also force framework settings to be stored in the private directory of the application. This can be done by changing the default path ofUserScope beforeQApplication is created:
#include <QSettings>#include <QDesktopServices>int main(int argc,char*argv[]){#ifdef Q_OS_SYMBIAN// Use QDesktopServices:storageLocation as QApplication is not yet createdQSettings::setPath(QSettings::NativeFormat,QSettings::UserScope,QDesktopServices::storageLocation(QDesktopServices::DataLocation)+"/settings");#endifQApplication app(argc, argv);...}
Note that this may affect framework libraries' functionality if they expect the settings to be shared between applications.
On Mac OS X, the global Qt settings (stored incom.trolltech.plist) are stored in the application settings file in two situations:
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'sInfo.plist file.
This feature is provided to ease the acceptance of Qt applications into the Mac App Store, as the default behaviour of storing global Qt settings in thecom.trolltech.plist file does not conform with Mac App Store file system usage requirements. For more information about submitting Qt applications to the Mac App Store, seePreparing a Qt application for Mac App Store submission.
WhileQSettings 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:
main() function and then use the defaultQSettings constructor. Another solution is to use preprocessor directives, for example:.plist files.See alsoQVariant,QSessionManager,Settings Editor Example, andApplication Example.
This enum type specifies the storage format used byQSettings.
| Constant | Value | Description |
|---|---|---|
QSettings::NativeFormat | 0 | Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry; on Mac OS X, this means the CFPreferences API; on Unix, this means textual configuration files in INI format. |
QSettings::IniFormat | 1 | Store the settings in INI files. |
QSettings::InvalidFormat | 16 | Special value returned byregisterFormat(). |
On Unix, NativeFormat and IniFormat mean the same thing, except that the file extension is different (.conf for NativeFormat,.ini for IniFormat).
The INI file format is a Windows file format that Qt supports on all platforms. In the absence of an INI standard, we try to follow what Microsoft does, with the following exceptions:
@-based syntax to encode the type. For example:pos= @Point(100100)
To minimize compatibility issues, any@ that doesn't appear at the first position in the value or that isn't followed by a Qt type (Point,Rect,Size, etc.) is treated as a normal character.
\) in file paths:windir= C:\WindowsQSettings always treats backslash as a special character and provides no API for reading or writing such entries.
% as an escape character in keys. In addition, if you save a top-level setting (a key with no slashes in it, e.g., "someKey"), it will appear in the INI file's "General" section. To avoid overwriting other keys, if you save something using the a key such as "General/someKey", the key will be located in the "%General" section,not in the "General" section.See alsoregisterFormat() andsetPath().
Typedef for a pointer to a function with the following signature:
ReadFunc is used inregisterFormat() as a pointer to a function that reads a set of key/value pairs.ReadFunc should read all the options in one pass, and return all the settings in theSettingsMap container, which is initially empty.
See alsoWriteFunc andregisterFormat().
This enum specifies whether settings are user-specific or shared by all users of the same system.
| Constant | Value | Description |
|---|---|---|
QSettings::UserScope | 0 | Store settings in a location specific to the current user (e.g., in the user's home directory). |
QSettings::SystemScope | 1 | Store settings in a global location, so that all users on the same machine access the same set of settings. |
See alsosetPath().
Typedef forQMap<QString,QVariant>.
See alsoregisterFormat().
The following status values are possible:
| Constant | Value | Description |
|---|---|---|
QSettings::NoError | 0 | No error occurred. |
QSettings::AccessError | 1 | An access error occurred (e.g. trying to write to a read-only file). |
QSettings::FormatError | 2 | A format error occurred (e.g. loading a malformed INI file). |
See alsostatus().
Typedef for a pointer to a function with the following signature:
WriteFunc is used inregisterFormat() as a pointer to a function that writes a set of key/value pairs.WriteFunc is only called once, so you need to output the settings in one go.
See alsoReadFunc andregisterFormat().
Constructs aQSettings object for accessing settings of the application calledapplication from the organization calledorganization, and with parentparent.
Example:
QSettings settings("Moose Tech","Facturo-Pro");
The scope is set toQSettings::UserScope, and the format is set toQSettings::NativeFormat (i.e. callingsetDefaultFormat() before calling this constructor has no effect).
See alsosetDefaultFormat() andFallback Mechanism.
Constructs aQSettings object for accessing settings of the application calledapplication from the organization calledorganization, and with parentparent.
Ifscope isQSettings::UserScope, theQSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. Ifscope isQSettings::SystemScope, theQSettings object ignores user-specific settings and provides access to system-wide settings.
The storage format is set toQSettings::NativeFormat (i.e. callingsetDefaultFormat() before calling this constructor has no effect).
If no application name is given, theQSettings object will only access the organization-widelocations.
See alsosetDefaultFormat().
Constructs aQSettings object for accessing settings of the application calledapplication from the organization calledorganization, and with parentparent.
Ifscope isQSettings::UserScope, theQSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. Ifscope isQSettings::SystemScope, theQSettings object ignores user-specific settings and provides access to system-wide settings.
Ifformat isQSettings::NativeFormat, the native API is used for storing settings. Ifformat isQSettings::IniFormat, the INI format is used.
If no application name is given, theQSettings object will only access the organization-widelocations.
Constructs aQSettings object for accessing the settings stored in the file calledfileName, with parentparent. If the file doesn't already exist, it is created.
Ifformat isQSettings::NativeFormat, the meaning offileName depends on the platform. On Unix,fileName is the name of an INI file. On Mac OS X,fileName is the name of a.plist file. On Windows,fileName is a path in the system registry.
Ifformat isQSettings::IniFormat,fileName is the name of an INI file.
Warning: This function is provided for convenience. It works well for accessing INI or.plist files generated by Qt, but might fail on some syntaxes found in such files originated by other programs. In particular, be aware of the following limitations:
@ character as a metacharacter in some contexts, to encode Qt-specific data types (e.g.,@Rect), and might therefore misinterpret it when it occurs in pure INI files.See alsofileName().
Constructs aQSettings object for accessing settings of the application and organization set previously with a call toQCoreApplication::setOrganizationName(),QCoreApplication::setOrganizationDomain(), andQCoreApplication::setApplicationName().
The scope isQSettings::UserScope and the format isdefaultFormat() (QSettings::NativeFormat by default). UsesetDefaultFormat() before calling this constructor to change the default format used by this constructor.
The code
QSettings settings("Moose Soft","Facturo-Pro");
is equivalent to
QCoreApplication::setOrganizationName("Moose Soft");QCoreApplication::setApplicationName("Facturo-Pro");QSettings settings;
IfQCoreApplication::setOrganizationName() andQCoreApplication::setApplicationName() has not been previously called, theQSettings object will not be able to read or write any settings, andstatus() will returnAccessError.
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 alsoQCoreApplication::setOrganizationName(),QCoreApplication::setOrganizationDomain(),QCoreApplication::setApplicationName(), andsetDefaultFormat().
Destroys theQSettings object.
Any unsaved changes will eventually be written to permanent storage.
See alsosync().
Returns a list of all keys, including subkeys, that can be read using theQSettings object.
Example:
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.allKeys();// keys: ["fridge/color", "fridge/size", "sofa", "tv"]
If a group is set usingbeginGroup(), only the keys in the group are returned, without the group prefix:
settings.beginGroup("fridge");keys= settings.allKeys();// keys: ["color", "size"]
See alsochildGroups() andchildKeys().
Returns the application name used for storing the settings.
This function was introduced in Qt 4.4.
See alsoQCoreApplication::applicationName(),format(),scope(), andorganizationName().
Appendsprefix to the current group.
The current group is automatically prepended to all keys specified toQSettings. In addition, query functions such aschildGroups(),childKeys(), andallKeys() 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/sizemainwindow/fullScreenoutputpanel/visibleCallendGroup() to reset the current group to what it was before the corresponding beginGroup() call. Groups can be nested.
See alsoendGroup() andgroup().
Addsprefix 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;...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();
UsebeginWriteArray() to write the array in the first place.
See alsobeginWriteArray(),endArray(), andsetArrayIndex().
Addsprefix to the current group and starts writing an array of sizesize. Ifsize 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;...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/sizelogins/1/userNamelogins/1/passwordlogins/2/userNamelogins/2/passwordlogins/3/userNamelogins/3/passwordTo read back an array, usebeginReadArray().
See alsobeginReadArray(),endArray(), andsetArrayIndex().
Returns a list of all key top-level groups that contain keys that can be read using theQSettings object.
Example:
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 usingbeginGroup(), 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 usingchildKeys() and childGroups() recursively.
See alsochildKeys() andallKeys().
Returns a list of all top-level keys that can be read using theQSettings object.
Example:
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 usingbeginGroup(), 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() andchildGroups() recursively.
See alsochildGroups() andallKeys().
Removes all entries in the primary location associated to thisQSettings object.
Entries in fallback locations are not removed.
If you only want to remove the entries in the currentgroup(), use remove("") instead.
See alsoremove() andsetFallbacksEnabled().
Returns true if there exists a setting calledkey; returns false otherwise.
If a group is set usingbeginGroup(),key is taken to be relative to that group.
Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see theSection and Key Syntax rules.
See alsovalue() andsetValue().
[static]Format QSettings::defaultFormat()Returns default file format used for storing settings for theQSettings(QObject *) constructor. If no default format is set,QSettings::NativeFormat is used.
This function was introduced in Qt 4.4.
See alsosetDefaultFormat() andformat().
Closes the array that was started usingbeginReadArray() orbeginWriteArray().
See alsobeginReadArray() andbeginWriteArray().
Resets the group to what it was before the correspondingbeginGroup() 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 alsobeginGroup() andgroup().
[virtual protected]bool QSettings::event(QEvent * event)Reimplemented fromQObject::event().
Returns true if fallbacks are enabled; returns false otherwise.
By default, fallbacks are enabled.
See alsosetFallbacksEnabled().
Returns the path where settings written using thisQSettings object are stored.
On Windows, if the format isQSettings::NativeFormat, the return value is a system registry path, not a file path.
See alsoisWritable() andformat().
Returns the format used for storing the settings.
This function was introduced in Qt 4.4.
See alsodefaultFormat(),fileName(),scope(),organizationName(), andapplicationName().
Returns the current group.
See alsobeginGroup() andendGroup().
Returns the codec that is used for accessing INI files. By default, no codec is used, so a null pointer is returned.
This function was introduced in Qt 4.5.
See alsosetIniCodec().
Returns true if settings can be written using thisQSettings object; returns false otherwise.
One reason why isWritable() might return false is ifQSettings operates on a read-only file.
Warning: This function is not perfectly reliable, because the file permissions can change at any time.
See alsofileName(),status(), andsync().
Returns the organization name used for storing the settings.
This function was introduced in Qt 4.4.
See alsoQCoreApplication::organizationName(),format(),scope(), andapplicationName().
[static]Format QSettings::registerFormat(constQString & extension,ReadFunc readFunc,WriteFunc writeFunc,Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive)Registers a custom storage format. On success, returns a special Format value that can then be passed to theQSettings constructor. On failure, returnsInvalidFormat.
Theextension is the file extension associated to the format (without the '.').
ThereadFunc andwriteFunc parameters are pointers to functions that read and write a set of key/value pairs. TheQIODevice parameter to the read and write functions is always opened in binary mode (i.e., without theQIODevice::Text flag).
ThecaseSensitivity parameter specifies whether keys are case sensitive or not. This makes a difference when looking up values usingQSettings. The default is case sensitive.
By default, if you use one of the constructors that work in terms of an organization name and an application name, the file system locations used are the same as forIniFormat. UsesetPath() to specify other locations.
Example:
bool readXmlFile(QIODevice&device,QSettings::SettingsMap&map);bool writeXmlFile(QIODevice&device,constQSettings::SettingsMap&map);int main(int argc,char*argv[]){constQSettings::Format XmlFormat=QSettings::registerFormat("xml", readXmlFile, writeXmlFile);QSettings settings(XmlFormat,QSettings::UserScope,"MySoft","Star Runner");...}
Note: This function isthread-safe.
This function was introduced in Qt 4.1.
See alsosetPath().
Removes the settingkey and any sub-settings ofkey.
Example:
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"]
Be aware that if one of the fallback locations contains a setting with the same key, that setting will be visible after calling remove().
Ifkey is an empty string, all keys in the currentgroup() are removed. For example:
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"]
Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see theSection and Key Syntax rules.
See alsosetValue(),value(), andcontains().
Returns the scope used for storing the settings.
This function was introduced in Qt 4.4.
See alsoformat(),organizationName(), andapplicationName().
Sets the current array index toi. Calls to functions such assetValue(),value(),remove(), andcontains() will operate on the array entry at that index.
You must callbeginReadArray() orbeginWriteArray() before you can call this function.
[static]void QSettings::setDefaultFormat(Format format)Sets the default file format to the givenformat, which is used for storing settings for theQSettings(QObject *) constructor.
If no default format is set,QSettings::NativeFormat is used. See the documentation for theQSettings constructor you are using to see if that constructor will ignore this function.
This function was introduced in Qt 4.4.
See alsodefaultFormat() andformat().
Sets whether fallbacks are enabled tob.
By default, fallbacks are enabled.
See alsofallbacksEnabled().
Sets the codec for accessing INI files (including.conf files on Unix) tocodec. 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 theQSettings object, before accessing any data.
This function was introduced in Qt 4.5.
See alsoiniCodec().
This is an overloaded function.
Sets the codec for accessing INI files (including.conf files on Unix) to theQTextCodec for the encoding specified bycodecName. Common values forcodecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.
This function was introduced in Qt 4.5.
See alsoQTextCodec::codecForName().
[static]void QSettings::setPath(Format format,Scope scope, constQString & path)Sets the path used for storing settings for the givenformat andscope, topath. Theformat can be a custom format.
The table below summarizes the default values:
| Platform | Format | Scope | Path |
|---|---|---|---|
| Windows | IniFormat | UserScope | %APPDATA% |
| SystemScope | %COMMON_APPDATA% | ||
| Unix | NativeFormat,IniFormat | UserScope | $HOME/.config |
| SystemScope | /etc/xdg | ||
| Qt for Embedded Linux | NativeFormat,IniFormat | UserScope | $HOME/Settings |
| SystemScope | /etc/xdg | ||
| Mac OS X | IniFormat | UserScope | $HOME/.config |
| SystemScope | /etc/xdg | ||
| Symbian | NativeFormat,IniFormat | UserScope | c:/data/.config |
| SystemScope | <drive>/private/<uid> |
The defaultUserScope paths on Unix and Mac OS X ($HOME/.config or $HOME/Settings) can be overridden by the user by setting theXDG_CONFIG_HOME environment variable. The defaultSystemScope paths on Unix and Mac OS X (/etc/xdg) can be overridden when building the Qt library using theconfigure script's--sysconfdir flag (seeQLibraryInfo for details).
Setting theNativeFormat paths on Windows and Mac OS X has no effect.
Warning: This function doesn't affect existingQSettings objects.
This function was introduced in Qt 4.1.
See alsoregisterFormat().
Sets the value of settingkey tovalue. If thekey already exists, the previous value is overwritten.
Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see theSection and Key Syntax rules.
Example:
QSettings settings;settings.setValue("interval",30);settings.value("interval").toInt();// returns 30settings.setValue("interval",6.55);settings.value("interval").toDouble();// returns 6.55
See alsovalue(),remove(), andcontains().
Returns a status code indicating the first error that was met byQSettings, orQSettings::NoError if no error occurred.
Be aware thatQSettings delays performing some operations. For this reason, you might want to callsync() to ensure that the data stored inQSettings is written to disk before calling status().
See alsosync().
Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application.
This function is called automatically fromQSettings's destructor and by the event loop at regular intervals, so you normally don't need to call it yourself.
See alsostatus().
Returns the value for settingkey. If the setting doesn't exist, returnsdefaultValue.
If no default value is specified, a defaultQVariant is returned.
Note that the Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, see theSection and Key Syntax rules.
Example:
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.