Qt 4.8
Public Types | Public Functions | Static Public Functions | Protected Functions | List of all members
QSettings Class Reference

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

#include <qsettings.h>

Inheritance diagram for QSettings:
QObject

Public Types

enum  Format {
  NativeFormat, IniFormat, InvalidFormat = 16, CustomFormat1,
  CustomFormat2, CustomFormat3, CustomFormat4, CustomFormat5,
  CustomFormat6, CustomFormat7, CustomFormat8, CustomFormat9,
  CustomFormat10, CustomFormat11, CustomFormat12, CustomFormat13,
  CustomFormat14, CustomFormat15, CustomFormat16
}
 This enum type specifies the storage format used by QSettings. More...
 
typedef bool(* ReadFunc) (QIODevice &device, SettingsMap &map)
 Typedef for a pointer to a function with the following signature: More...
 
enum  Scope { UserScope, SystemScope }
 ) in file paths: More...
 
typedef QMap< QString, QVariantSettingsMap
 Typedef for QMap<QString, QVariant>. More...
 
enum  Status { NoError = 0, AccessError, FormatError }
 The following status values are possible: More...
 
typedef bool(* WriteFunc) (QIODevice &device, const SettingsMap &map)
 Typedef for a pointer to a function with the following signature: More...
 

Public Functions

QStringList allKeys () const
 Returns a list of all keys, including subkeys, that can be read using the QSettings object. More...
 
QString applicationName () const
 Returns the application name used for storing the settings. More...
 
void beginGroup (const QString &prefix)
 Appends prefix to the current group. More...
 
int beginReadArray (const QString &prefix)
 Adds prefix to the current group and starts reading from an array. More...
 
void beginWriteArray (const QString &prefix, int size=-1)
 Adds prefix to the current group and starts writing an array of size size. More...
 
QStringList childGroups () const
 Returns a list of all key top-level groups that contain keys that can be read using the QSettings object. More...
 
QStringList childKeys () const
 Returns a list of all top-level keys that can be read using the QSettings object. More...
 
void clear ()
 Removes all entries in the primary location associated to this QSettings object. More...
 
bool contains (const QString &key) const
 Returns true if there exists a setting called key; returns false otherwise. More...
 
void endArray ()
 Closes the array that was started using beginReadArray() or beginWriteArray(). More...
 
void endGroup ()
 Resets the group to what it was before the corresponding beginGroup() call. More...
 
bool fallbacksEnabled () const
 Returns true if fallbacks are enabled; returns false otherwise. More...
 
QString fileName () const
 Returns the path where settings written using this QSettings object are stored. More...
 
Format format () const
 Returns the format used for storing the settings. More...
 
QString group () const
 Returns the current group. More...
 
QTextCodeciniCodec () const
 Returns the codec that is used for accessing INI files. More...
 
bool isWritable () const
 Returns true if settings can be written using this QSettings object; returns false otherwise. More...
 
QString organizationName () const
 Returns the organization name used for storing the settings. More...
 
 QSettings (const QString &organization, const QString &application=QString(), QObject *parent=0)
 Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent. More...
 
 QSettings (Scope scope, const QString &organization, const QString &application=QString(), QObject *parent=0)
 Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent. More...
 
 QSettings (Format format, Scope scope, const QString &organization, const QString &application=QString(), QObject *parent=0)
 Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent. More...
 
 QSettings (const QString &fileName, Format format, QObject *parent=0)
 Constructs a QSettings object for accessing the settings stored in the file called fileName, with parent parent. More...
 
 QSettings (QObject *parent=0)
 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(). More...
 
void remove (const QString &key)
 Removes the setting key and any sub-settings of key. More...
 
Scope scope () const
 Returns the scope used for storing the settings. More...
 
void setArrayIndex (int i)
 Sets the current array index to i. More...
 
void setFallbacksEnabled (bool b)
 Sets whether fallbacks are enabled to b. More...
 
void setIniCodec (QTextCodec *codec)
 Sets the codec for accessing INI files (including . More...
 
void setIniCodec (const char *codecName)
 Sets the codec for accessing INI files (including . More...
 
void setValue (const QString &key, const QVariant &value)
 Sets the value of setting key to value. More...
 
Status status () const
 Returns a status code indicating the first error that was met by QSettings, or QSettings::NoError if no error occurred. More...
 
void sync ()
 Writes any unsaved changes to permanent storage, and reloads any settings that have been changed in the meantime by another application. More...
 
QVariant value (const QString &key, const QVariant &defaultValue=QVariant()) const
 Returns the value for setting key. More...
 
 ~QSettings ()
 Destroys the QSettings object. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static Format defaultFormat ()
 
static Format registerFormat (const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity=Qt::CaseSensitive)
 Registers a custom storage format. More...
 
static void setDefaultFormat (Format format)
 
static void setPath (Format format, Scope scope, const QString &path)
 Sets the path used for storing settings for the given format and scope, to path. More...
 
static void setSystemIniPath (const QString &dir)
 Use setPath() instead. More...
 
static void setUserIniPath (const QString &dir)
 Use setPath() instead. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Functions

bool event (QEvent *event)
 Reimplemented Function More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Additional Inherited Members

- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QSettings class provides persistent platform-independent application settings.

Note
This class or function is reentrant.

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 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.

section1

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:

...

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 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 QtCore library, it cannot provide conversion functions to data types such as QColor, QImage, and QPixmap, which are part of QtGui . In other words, there is no toColor(), toImage(), or toPixmap() functions in QVariant.

Instead, you can use the QVariant::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., 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() and qRegisterMetaTypeStreamOperators() 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 Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, follow these simple rules:

  1. Always refer to the same key using the same case. For example, if you refer to a key as "text fonts" in one place in your code, don't refer to it as "Text Fonts" somewhere else.

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

  3. 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->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 using beginGroup() and call endGroup() at the end. Here's the same example again, but this time using the group mechanism:

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

If a group is set using beginGroup(), the behavior of most functions changes consequently. Groups can be set recursively.

In addition to groups, 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:

  1. a user-specific location for the Star Runner application
  2. a user-specific location for all applications by MySoft
  3. a system-wide location for the Star Runner application
  4. 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");

The table below summarizes which QSettings objects access which location. "<b>X</b>" 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:

"MySoft", "Star Runner");

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

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->accept();
} else {
event->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. It uses advisory file locking and a smart merging algorithm to ensure data integrity. 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:

  1. $HOME/.config/MySoft/Star Runner.conf (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.conf)
  2. $HOME/.config/MySoft.conf (Qt for Embedded Linux: $HOME/Settings/MySoft.conf)
  3. /etc/xdg/MySoft/Star Runner.conf
  4. /etc/xdg/MySoft.conf

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

  1. $HOME/Library/Preferences/com.MySoft.Star Runner.plist
  2. $HOME/Library/Preferences/com.MySoft.plist
  3. /Library/Preferences/com.MySoft.Star Runner.plist
  4. /Library/Preferences/com.MySoft.plist

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

  1. HKEY_CURRENT_USER\Software\MySoft\Star Runner
  2. HKEY_CURRENT_USER\Software\MySoft
  3. HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
  4. HKEY_LOCAL_MACHINE\Software\MySoft
Note
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 (see Platform Limitations). 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 and Mac OS X:

  1. $HOME/.config/MySoft/Star Runner.ini (Qt for Embedded Linux: $HOME/Settings/MySoft/Star Runner.ini)
  2. $HOME/.config/MySoft.ini (Qt for Embedded Linux: $HOME/Settings/MySoft.ini)
  3. /etc/xdg/MySoft/Star Runner.ini
  4. /etc/xdg/MySoft.ini

On Windows, the following files are used:

  1. APPDATA%/MySoft/Star Runner.ini
  2. APPDATA%/MySoft.ini
  3. COMMON_APPDATA%/MySoft/Star Runner.ini
  4. COMMON_APPDATA%/MySoft.ini

The APPDATA% path is usually C:\Documents and Settings\User Name\Application Data; the COMMON_APPDATA% path is usually C:\Documents and Settings\All Users\Application Data.

On BlackBerry only a single file is used (see Platform Limitations). If the file format is IniFormat, this is "Settings/MySoft/Star Runner.ini" in the application's home directory.

On Symbian, the following files are used for both IniFormat and NativeFormat (in this example, we assume that the application is installed on the e-drive and its Secure ID is 0xECB00931):

  1. c:/data/.config/MySoft/Star Runner.conf
  2. c:/data/.config/MySoft.conf
  3. e:/private/ecb00931/MySoft/Star Runner.conf
  4. e:/private/ecb00931/MySoft.conf

The SystemScope 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 for SystemScope is c:.

Note
Symbian SystemScope 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 using setPath(). On Unix and Mac OS X, the user can override them by setting the XDG_CONFIG_HOME environment variable; see setPath() for details.

.plist-Files-Directly

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",

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. For example:

QSettings settings("/Users/petra/misc/myapp.plist",

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",

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.

Securing application settings in Symbian

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 the UserScope to c:/private/ecb00931/MySoft.conf (provided the application is installed on the c-drive and its Secure ID is 0xECB00931:

QSettings settings(QApplication::applicationDirPath() + "/MySoft.conf");

Framework libraries (like Qt itself) may store configuration and cache settings using UserScope, 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 of UserScope before QApplication is created:

#include <QSettings>
#include <QDesktopServices>
int main(int argc, char *argv[])
{
#ifdef Q_OS_SYMBIAN
// Use QDesktopServices:storageLocation as QApplication is not yet created
#endif
QApplication app(argc, argv);
...
}

Note that this may affect framework libraries' functionality if they expect the settings to be shared between applications.

Changing the location of global Qt settings on Mac OS X

On Mac OS X, the global Qt settings (stored in com.trolltech.plist) are stored in the application settings file in two situations:

  1. If the application runs in a Mac OS X sandbox (on Mac OS X 10.7 or later) 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 Qt applications into the Mac App Store, as the default behaviour of storing global Qt settings in the com.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, see Preparing a Qt application for Mac App Store submission.

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:

See also
QVariant, QSessionManager, {Settings Editor Example}, {Application Example}

Definition at line 73 of file qsettings.h.

Typedefs

◆ ReadFunc

QSettings::ReadFunc

Typedef for a pointer to a function with the following signature:

bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map);

ReadFunc is used in registerFormat() 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 the SettingsMap container, which is initially empty.

See also
WriteFunc, registerFormat()

Definition at line 191 of file qsettings.h.

◆ SettingsMap

Typedef for QMap<QString, QVariant>.

See also
registerFormat()

Definition at line 190 of file qsettings.h.

◆ WriteFunc

QSettings::WriteFunc

Typedef for a pointer to a function with the following signature:

bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map);

WriteFunc is used in registerFormat() 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 also
ReadFunc, registerFormat()

Definition at line 192 of file qsettings.h.

Enumerations

◆ Format

This enum type specifies the storage format used by QSettings.

  • NativeFormat 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.
  • IniFormat Store the settings in INI files.
  • InvalidFormat Special value returned by registerFormat().
  • CustomFormat1
  • CustomFormat2
  • CustomFormat3
  • CustomFormat4
  • CustomFormat5
  • CustomFormat6
  • CustomFormat7
  • CustomFormat8
  • CustomFormat9
  • CustomFormat10
  • CustomFormat11
  • CustomFormat12
  • CustomFormat13
  • CustomFormat14
  • CustomFormat15
  • CustomFormat16

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:

  • If you store types that QVariant can't convert to QString (e.g., QPoint, QRect, and QSize), Qt uses an </tt>-based syntax to encode the type. For example:

    pos = @Point(100 100)

    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.

  • Although backslash is a special character in INI files, most Windows applications don't escape backslashes ({
Enumerator
NativeFormat 
IniFormat 
InvalidFormat 
CustomFormat1 
CustomFormat2 
CustomFormat3 
CustomFormat4 
CustomFormat5 
CustomFormat6 
CustomFormat7 
CustomFormat8 
CustomFormat9 
CustomFormat10 
CustomFormat11 
CustomFormat12 
CustomFormat13 
CustomFormat14 
CustomFormat15 
CustomFormat16 

Definition at line 92 of file qsettings.h.

◆ Scope

) in file paths:

windir = C:\Windows

QSettings always treats backslash as a special character and provides no API for reading or writing such entries.

The INI file format has severe restrictions on the syntax of a key. Qt 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 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.

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.

  • UserScope Store settings in a location specific to the current user (e.g., in the user's home directory).
  • SystemScope Store settings in a global location, so that all users on the same machine access the same set of settings.
  • User
  • Global
See also
setPath()
Enumerator
UserScope 
SystemScope 

Definition at line 115 of file qsettings.h.

115  {
116  UserScope,
118 #ifdef QT3_SUPPORT
119  ,
120  User = UserScope,
121  Global = SystemScope
122 #endif
123  };

◆ Status

The following status values are possible:

  • NoError No error occurred.
  • AccessError An access error occurred (e.g. trying to write to a read-only file).
  • FormatError A format error occurred (e.g. loading a malformed INI file).
See also
status()
Enumerator
NoError 
AccessError 
FormatError 

Definition at line 86 of file qsettings.h.

Constructors and Destructors

◆ QSettings() [1/5]

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

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

Example:

QSettings settings("Moose Tech", "Facturo-Pro");

The scope is set to QSettings::UserScope, and the format is set to QSettings::NativeFormat (i.e. calling setDefaultFormat() before calling this constructor has no effect).

See also
setDefaultFormat(), {Fallback Mechanism}

Definition at line 2666 of file qsettings.cpp.

Referenced by QSettings().

2667  : QObject(*QSettingsPrivate::create(NativeFormat, UserScope, organization, application),
2668  parent)
2669 {
2670 }
static QSettingsPrivate * create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application)
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ QSettings() [2/5]

QSettings::QSettings ( Scope  scope,
const QString organization,
const QString application = QString(),
QObject parent = 0 
)

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

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

The storage format is set to QSettings::NativeFormat (i.e. calling setDefaultFormat() before calling this constructor has no effect).

If no application name is given, the QSettings object will only access the organization-wide Fallback Mechanism{locations}.

See also
setDefaultFormat()

Definition at line 2691 of file qsettings.cpp.

2693  : QObject(*QSettingsPrivate::create(NativeFormat, scope, organization, application), parent)
2694 {
2695 }
Scope scope() const
Returns the scope used for storing the settings.
Definition: qsettings.cpp:2929
static QSettingsPrivate * create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application)
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ QSettings() [3/5]

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

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

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

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

If no application name is given, the QSettings object will only access the organization-wide Fallback Mechanism{locations}.

Definition at line 2715 of file qsettings.cpp.

2717  : QObject(*QSettingsPrivate::create(format, scope, organization, application), parent)
2718 {
2719 }
Scope scope() const
Returns the scope used for storing the settings.
Definition: qsettings.cpp:2929
static QSettingsPrivate * create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application)
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ QSettings() [4/5]

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

Constructs a QSettings object for accessing the settings stored in the file called fileName, with parent parent.

If the file doesn't already exist, it is created.

If format is QSettings::NativeFormat, the meaning of fileName 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.

If format is QSettings::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:
  • QSettings provides no way of reading INI "path" entries, i.e., entries with unescaped slash characters. (This is because these entries are ambiguous and cannot be resolved automatically.)
  • In INI files, QSettings uses the @ character as a metacharacter in some contexts, to encode Qt-specific data types (e.g., ), and might therefore misinterpret it when it occurs in pure INI files.
See also
fileName()

Definition at line 2751 of file qsettings.cpp.

2752  : QObject(*QSettingsPrivate::create(fileName, format), parent)
2753 {
2754 }
static QSettingsPrivate * create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application)
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

◆ QSettings() [5/5]

QSettings::QSettings ( QObject parent = 0)
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 code

QSettings settings("Moose Soft", "Facturo-Pro");

is equivalent to

If QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName() has not been previously called, the QSettings object will not be able to read or write any settings, and status() will return 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()

Definition at line 2790 of file qsettings.cpp.

2792 #ifdef Q_OS_MAC
2796 #else
2800 #endif
2802  parent)
2803 {
2804 }
static QSettingsPrivate * create(QSettings::Format format, QSettings::Scope scope, const QString &organization, const QString &application)
#define Q_OS_MAC
Defined on MAC OS (synonym for Darwin).
Definition: qglobal.h:274
static bool isEmpty(const char *str)
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
static QSettings::Format globalDefaultFormat
Definition: qsettings.cpp:126
static QString organizationDomain()
static QString organizationName()
static QString applicationName()

◆ ~QSettings()

QSettings::~QSettings ( )

Destroys the QSettings object.

Any unsaved changes will eventually be written to permanent storage.

See also
sync()

Definition at line 2841 of file qsettings.cpp.

2842 {
2843  Q_D(QSettings);
2844  if (d->pendingChanges) {
2845  QT_TRY {
2846  d->flush();
2847  } QT_CATCH(...) {
2848  ; // ok. then don't flush but at least don't throw in the destructor
2849  }
2850  }
2851 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482
#define QT_CATCH(A)
Definition: qglobal.h:1537
#define QT_TRY
Definition: qglobal.h:1536

Functions

◆ allKeys()

QStringList QSettings::allKeys ( ) const

Returns a list of all keys, including subkeys, that can be read using the QSettings 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 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()

Definition at line 3240 of file qsettings.cpp.

3241 {
3242  Q_D(const QSettings);
3243  return d->children(d->groupPrefix, QSettingsPrivate::AllKeys);
3244 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ applicationName()

QString QSettings::applicationName ( ) const

Returns the application name used for storing the settings.

Since
4.4
See also
QCoreApplication::applicationName(), format(), scope(), organizationName()

Definition at line 2961 of file qsettings.cpp.

2962 {
2963  Q_D(const QSettings);
2964  return d->applicationName;
2965 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ beginGroup()

void QSettings::beginGroup ( const QString prefix)

Appends prefix to the current group.

The current group is automatically prepended to all keys specified to QSettings. In addition, query functions such as childGroups(), childKeys(), and allKeys() are based on the group. By default, no group is set.

Groups are useful to avoid typing in the same setting paths over and over. For example:

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

This will set the value of three settings:

  • mainwindow/size
  • mainwindow/fullScreen
  • outputpanel/visible

Call endGroup() to reset the current group to what it was before the corresponding beginGroup() call. Groups can be nested.

See also
endGroup(), group()

Definition at line 3073 of file qsettings.cpp.

Referenced by fontPath(), QFileDialogPrivate::init(), QKde::kdeToolBarIconSize(), QKde::kdeToolButtonStyle(), QLibraryInfo::location(), QMultiInputContext::QMultiInputContext(), QPSPrintEnginePrivate::QPSPrintEnginePrivate(), QApplicationPrivate::qt_mac_apply_settings(), MetaObjectGenerator::readClassInfo(), QAxBase::setControl(), QGuiPlatformPlugin::systemIconThemeName(), QApplicationPrivate::x11_apply_settings(), and QFileDialog::~QFileDialog().

3074 {
3075  Q_D(QSettings);
3076  d->beginGroupOrArray(QSettingsGroup(d->normalizedKey(prefix)));
3077 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ beginReadArray()

int QSettings::beginReadArray ( const QString prefix)

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

Returns the size of the array.

Example:

struct Login {
QString userName;
QString password;
};
QList<Login> logins;
...
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()

Definition at line 3129 of file qsettings.cpp.

3130 {
3131  Q_D(QSettings);
3132  d->beginGroupOrArray(QSettingsGroup(d->normalizedKey(prefix), false));
3133  return value(QLatin1String("size")).toInt();
3134 }
double d
Definition: qnumeric_p.h:62
QVariant value(const QString &key, const QVariant &defaultValue=QVariant()) const
Returns the value for setting key.
Definition: qsettings.cpp:3460
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
int toInt(bool *ok=0) const
Returns the variant as an int if the variant has type() Int , Bool , ByteArray , Char ...
Definition: qvariant.cpp:2625

◆ beginWriteArray()

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

Adds prefix to the current group and starts writing an array of size size.

If size is -1 (the default), it is automatically determined based on the indexes of the entries written.

If you have many occurrences of a certain set of keys, you can use arrays to make your life easier. For example, let's suppose that you want to save a 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()

Definition at line 3165 of file qsettings.cpp.

3166 {
3167  Q_D(QSettings);
3168  d->beginGroupOrArray(QSettingsGroup(d->normalizedKey(prefix), size < 0));
3169 
3170  if (size < 0)
3171  remove(QLatin1String("size"));
3172  else
3173  setValue(QLatin1String("size"), size);
3174 }
double d
Definition: qnumeric_p.h:62
void setValue(const QString &key, const QVariant &value)
Sets the value of setting key to value.
Definition: qsettings.cpp:3328
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482

◆ childGroups()

QStringList QSettings::childGroups ( ) const

Returns a list of all key top-level groups that contain keys that can be read using the QSettings 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 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()

Definition at line 3288 of file qsettings.cpp.

Referenced by QLibraryInfo::location(), MetaObjectGenerator::readClassInfo(), and QAxBase::setControl().

3289 {
3290  Q_D(const QSettings);
3291  return d->children(d->groupPrefix, QSettingsPrivate::ChildGroups);
3292 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ childKeys()

QStringList QSettings::childKeys ( ) const

Returns a list of all top-level keys that can be read using the QSettings 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 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()

Definition at line 3264 of file qsettings.cpp.

Referenced by QApplicationPrivate::qt_mac_apply_settings(), and QApplicationPrivate::x11_apply_settings().

3265 {
3266  Q_D(const QSettings);
3267  return d->children(d->groupPrefix, QSettingsPrivate::ChildKeys);
3268 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ clear()

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

Definition at line 2864 of file qsettings.cpp.

2865 {
2866  Q_D(QSettings);
2867  d->clear();
2868  d->requestUpdate();
2869 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ contains()

bool QSettings::contains ( const QString key) const

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

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

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

See also
value(), setValue()

Definition at line 3394 of file qsettings.cpp.

Referenced by QLocalServerPrivate::listen(), QLibraryInfo::location(), qt_applyFontDatabaseSettings(), and QLocalServerPrivate::removeServer().

3395 {
3396  Q_D(const QSettings);
3397  QString k = d->actualKey(key);
3398  return d->get(k, 0);
3399 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482

◆ defaultFormat()

QSettings::Format QSettings::defaultFormat ( )
static
Since
4.4

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

Definition at line 3494 of file qsettings.cpp.

3495 {
3496  return globalDefaultFormat;
3497 }
static QSettings::Format globalDefaultFormat
Definition: qsettings.cpp:126

◆ endArray()

void QSettings::endArray ( )

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

See also
beginReadArray(), beginWriteArray()

Definition at line 3182 of file qsettings.cpp.

3183 {
3184  Q_D(QSettings);
3185  if (d->groupStack.isEmpty()) {
3186  qWarning("QSettings::endArray: No matching beginArray()");
3187  return;
3188  }
3189 
3190  QSettingsGroup group = d->groupStack.top();
3191  int len = group.toString().size();
3192  d->groupStack.pop();
3193  if (len > 0)
3194  d->groupPrefix.truncate(d->groupPrefix.size() - (len + 1));
3195 
3196  if (group.arraySizeGuess() != -1)
3197  setValue(group.name() + QLatin1String("/size"), group.arraySizeGuess());
3198 
3199  if (!group.isArray())
3200  qWarning("QSettings::endArray: Expected endGroup() instead");
3201 }
double d
Definition: qnumeric_p.h:62
void setValue(const QString &key, const QVariant &value)
Sets the value of setting key to value.
Definition: qsettings.cpp:3328
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
#define Q_D(Class)
Definition: qglobal.h:2482
int arraySizeGuess() const
Definition: qsettings_p.h:130
QString group() const
Returns the current group.
Definition: qsettings.cpp:3111
QString toString() const
Definition: qsettings_p.h:139
int size() const
Returns the number of characters in this string.
Definition: qstring.h:102
Q_CORE_EXPORT void qWarning(const char *,...)
QString name() const
Definition: qsettings_p.h:127
bool isArray() const
Definition: qsettings_p.h:129

◆ endGroup()

void QSettings::endGroup ( )

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

Example:

settings.beginGroup("alpha");
// settings.group() == "alpha"
settings.beginGroup("beta");
// settings.group() == "alpha/beta"
settings.endGroup();
// settings.group() == "alpha"
settings.endGroup();
// settings.group() == ""
See also
beginGroup(), group()

Definition at line 3089 of file qsettings.cpp.

Referenced by QLibraryInfo::location(), QApplicationPrivate::qt_mac_apply_settings(), MetaObjectGenerator::readClassInfo(), QAxBase::setControl(), and QApplicationPrivate::x11_apply_settings().

3090 {
3091  Q_D(QSettings);
3092  if (d->groupStack.isEmpty()) {
3093  qWarning("QSettings::endGroup: No matching beginGroup()");
3094  return;
3095  }
3096 
3097  QSettingsGroup group = d->groupStack.pop();
3098  int len = group.toString().size();
3099  if (len > 0)
3100  d->groupPrefix.truncate(d->groupPrefix.size() - (len + 1));
3101 
3102  if (group.isArray())
3103  qWarning("QSettings::endGroup: Expected endArray() instead");
3104 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482
QString group() const
Returns the current group.
Definition: qsettings.cpp:3111
QString toString() const
Definition: qsettings_p.h:139
int size() const
Returns the number of characters in this string.
Definition: qstring.h:102
Q_CORE_EXPORT void qWarning(const char *,...)
bool isArray() const
Definition: qsettings_p.h:129

◆ event()

bool QSettings::event ( QEvent event)
protectedvirtual

Reimplemented Function

Reimplemented from QObject.

Definition at line 3431 of file qsettings.cpp.

3432 {
3433  Q_D(QSettings);
3434  if (event->type() == QEvent::UpdateRequest) {
3435  d->update();
3436  return true;
3437  }
3438  return QObject::event(event);
3439 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
virtual bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
Definition: qobject.cpp:1200
#define Q_D(Class)
Definition: qglobal.h:2482
Type type() const
Returns the event type.
Definition: qcoreevent.h:303

◆ fallbacksEnabled()

bool QSettings::fallbacksEnabled ( ) const

Returns true if fallbacks are enabled; returns false otherwise.

By default, fallbacks are enabled.

See also
setFallbacksEnabled()

Definition at line 3421 of file qsettings.cpp.

3422 {
3423  Q_D(const QSettings);
3424  return d->fallbacks;
3425 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ fileName()

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

Definition at line 2897 of file qsettings.cpp.

2898 {
2899  Q_D(const QSettings);
2900  return d->fileName();
2901 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ format()

QSettings::Format QSettings::format ( ) const

Returns the format used for storing the settings.

Since
4.4
See also
defaultFormat(), fileName(), scope(), organizationName(), applicationName()

Definition at line 2913 of file qsettings.cpp.

Referenced by setDefaultFormat().

2914 {
2915  Q_D(const QSettings);
2916  return d->format;
2917 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ group()

QString QSettings::group ( ) const

Returns the current group.

See also
beginGroup(), endGroup()

Definition at line 3111 of file qsettings.cpp.

Referenced by endArray(), endGroup(), and remove().

3112 {
3113  Q_D(const QSettings);
3114  return d->groupPrefix.left(d->groupPrefix.size() - 1);
3115 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ iniCodec()

QTextCodec * QSettings::iniCodec ( ) const

Returns the codec that is used for accessing INI files.

Since
4.5

By default, no codec is used, so a null pointer is returned.

Definition at line 3023 of file qsettings.cpp.

3024 {
3025  Q_D(const QSettings);
3026  return d->iniCodec;
3027 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ isWritable()

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.

Warning
This function is not perfectly reliable, because the file permissions can change at any time.
See also
fileName(), status(), sync()

Definition at line 3306 of file qsettings.cpp.

Referenced by UpdateRegistry().

3307 {
3308  Q_D(const QSettings);
3309  return d->isWritable();
3310 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ organizationName()

QString QSettings::organizationName ( ) const

Returns the organization name used for storing the settings.

Since
4.4
See also
QCoreApplication::organizationName(), format(), scope(), applicationName()

Definition at line 2945 of file qsettings.cpp.

2946 {
2947  Q_D(const QSettings);
2948  return d->organizationName;
2949 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ registerFormat()

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

Registers a custom storage format.

Since
4.1
Note
This class or function is threadsafe.

On success, returns a special Format value that can then be passed to the QSettings constructor. On failure, returns InvalidFormat.

The extension is the file extension associated to the format (without the '.').

The readFunc and writeFunc parameters are pointers to functions that read and write a set of key/value pairs. The QIODevice parameter to the read and write functions is always opened in binary mode (i.e., 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 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 for IniFormat. Use setPath() to specify other locations.

Example:

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, "MySoft",
"Star Runner");
...
}
See also
setPath()

Definition at line 3663 of file qsettings.cpp.

3666 {
3667 #ifdef QT_QSETTINGS_ALWAYS_CASE_SENSITIVE_AND_FORGET_ORIGINAL_KEY_ORDER
3668  Q_ASSERT(caseSensitivity == Qt::CaseSensitive);
3669 #endif
3670 
3671  QMutexLocker locker(globalMutex());
3672  CustomFormatVector *customFormatVector = customFormatVectorFunc();
3673  int index = customFormatVector->size();
3674  if (index == 16) // the QSettings::Format enum has room for 16 custom formats
3675  return QSettings::InvalidFormat;
3676 
3678  info.extension = QLatin1Char('.');
3679  info.extension += extension;
3680  info.readFunc = readFunc;
3681  info.writeFunc = writeFunc;
3682  info.caseSensitivity = caseSensitivity;
3683  customFormatVector->append(info);
3684 
3685  return QSettings::Format((int)QSettings::CustomFormat1 + index);
3686 }
static mach_timebase_info_data_t info
QSettings::WriteFunc writeFunc
Definition: qsettings.cpp:112
Format
This enum type specifies the storage format used by QSettings.
Definition: qsettings.h:92
QSettings::ReadFunc readFunc
Definition: qsettings.cpp:111
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
The QVector class is a template class that provides a dynamic array.
Definition: qdatastream.h:64
Qt::CaseSensitivity caseSensitivity
Definition: qsettings.cpp:113
void append(const T &t)
Inserts value at the end of the vector.
Definition: qvector.h:573
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
quint16 index
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ remove()

void QSettings::remove ( const QString key)

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

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

If key is an empty string, all keys in the current group() 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 the Section and Key Syntax rules.

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

Definition at line 3359 of file qsettings.cpp.

Referenced by QLocalServerPrivate::closeServer(), and QLocalServerPrivate::removeServer().

3360 {
3361  Q_D(QSettings);
3362  /*
3363  We cannot use actualKey(), because remove() supports empty
3364  keys. The code is also tricky because of slash handling.
3365  */
3366  QString theKey = d->normalizedKey(key);
3367  if (theKey.isEmpty())
3368  theKey = group();
3369  else
3370  theKey.prepend(d->groupPrefix);
3371 
3372  if (theKey.isEmpty()) {
3373  d->clear();
3374  } else {
3375  d->remove(theKey);
3376  }
3377  d->requestUpdate();
3378 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
QString & prepend(QChar c)
Definition: qstring.h:261
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482
QString group() const
Returns the current group.
Definition: qsettings.cpp:3111
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704

◆ scope()

QSettings::Scope QSettings::scope ( ) const

Returns the scope used for storing the settings.

Since
4.4
See also
format(), organizationName(), applicationName()

Definition at line 2929 of file qsettings.cpp.

2930 {
2931  Q_D(const QSettings);
2932  return d->scope;
2933 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ setArrayIndex()

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.

Definition at line 3211 of file qsettings.cpp.

3212 {
3213  Q_D(QSettings);
3214  if (d->groupStack.isEmpty() || !d->groupStack.top().isArray()) {
3215  qWarning("QSettings::setArrayIndex: Missing beginArray()");
3216  return;
3217  }
3218 
3219  QSettingsGroup &top = d->groupStack.top();
3220  int len = top.toString().size();
3221  top.setArrayIndex(qMax(i, 0));
3222  d->groupPrefix.replace(d->groupPrefix.size() - len - 1, len, top.toString());
3223 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
QString toString() const
Definition: qsettings_p.h:139
int size() const
Returns the number of characters in this string.
Definition: qstring.h:102
Q_CORE_EXPORT void qWarning(const char *,...)
void setArrayIndex(int i)
Definition: qsettings_p.h:131

◆ setDefaultFormat()

void QSettings::setDefaultFormat ( Format  format)
static
Since
4.4

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 function.

See also
format()

Definition at line 3481 of file qsettings.cpp.

3482 {
3484 }
Format format() const
Returns the format used for storing the settings.
Definition: qsettings.cpp:2913
static QSettings::Format globalDefaultFormat
Definition: qsettings.cpp:126

◆ setFallbacksEnabled()

void QSettings::setFallbacksEnabled ( bool  b)

Sets whether fallbacks are enabled to b.

By default, fallbacks are enabled.

See also
fallbacksEnabled()

Definition at line 3408 of file qsettings.cpp.

3409 {
3410  Q_D(QSettings);
3411  d->fallbacks = !!b;
3412 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ setIniCodec() [1/2]

void QSettings::setIniCodec ( QTextCodec codec)

Sets the codec for accessing INI files (including .

Since
4.5

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

Definition at line 2986 of file qsettings.cpp.

2987 {
2988  Q_D(QSettings);
2989  d->iniCodec = codec;
2990 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482
static QTextCodec * codec(MYSQL *mysql)
Definition: qsql_mysql.cpp:220

◆ setIniCodec() [2/2]

void QSettings::setIniCodec ( const char *  codecName)

Sets the codec for accessing INI files (including .

Since
4.5 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

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 isn't recognized, nothing happens.

See also
QTextCodec::codecForName()

Definition at line 3006 of file qsettings.cpp.

3007 {
3008  Q_D(QSettings);
3009  if (QTextCodec *codec = QTextCodec::codecForName(codecName))
3010  d->iniCodec = codec;
3011 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482
static QTextCodec * codec(MYSQL *mysql)
Definition: qsql_mysql.cpp:220
static QTextCodec * codecForName(const QByteArray &name)
Searches all installed QTextCodec objects and returns the one which best matches name; the match is c...
The QTextCodec class provides conversions between text encodings.
Definition: qtextcodec.h:62

◆ setPath()

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.

Since
4.1

The format 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 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. The default SystemScope paths on Unix and Mac OS X (/etc/xdg) can be overridden when building the Qt library using the configure script's –sysconfdir flag (see QLibraryInfo for details).

Setting the NativeFormat paths on Windows and Mac OS X has no effect.

Warning
This function doesn't affect existing QSettings objects.
See also
registerFormat()

Definition at line 3578 of file qsettings.cpp.

Referenced by setSystemIniPath(), and setUserIniPath().

3579 {
3580  QMutexLocker locker(globalMutex());
3581  PathHash *pathHash = pathHashFunc();
3582  if (pathHash->isEmpty())
3583  initDefaultPaths(&locker);
3584  pathHash->insert(pathHashKey(format, scope), path + QDir::separator());
3585 }
Scope scope() const
Returns the scope used for storing the settings.
Definition: qsettings.cpp:2929
static void initDefaultPaths(QMutexLocker *locker)
Definition: qsettings.cpp:1073
static QChar separator()
Returns the native directory separator: "/" under Unix (including Mac OS X) and "\\" under Windows...
Definition: qdir.cpp:1831
iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:753
bool isEmpty() const
Returns true if the hash contains no items; otherwise returns false.
Definition: qhash.h:297
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
static int pathHashKey(QSettings::Format format, QSettings::Scope scope)
Definition: qsettings.cpp:1068

◆ setSystemIniPath()

void QSettings::setSystemIniPath ( const QString dir)
static

Use setPath() instead.

setSystemIniPath(path); setPath(QSettings::NativeFormat, QSettings::SystemScope, path); setPath(QSettings::IniFormat, QSettings::SystemScope, path);

Definition at line 3514 of file qsettings.cpp.

3515 {
3516  setPath(IniFormat, SystemScope, dir);
3517 #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
3519 #endif
3520 }
static void setPath(Format format, Scope scope, const QString &path)
Sets the path used for storing settings for the given format and scope, to path.
Definition: qsettings.cpp:3578

◆ setUserIniPath()

void QSettings::setUserIniPath ( const QString dir)
static

Use setPath() instead.

Definition at line 3531 of file qsettings.cpp.

3532 {
3533  setPath(IniFormat, UserScope, dir);
3534 #if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
3536 #endif
3537 }
static void setPath(Format format, Scope scope, const QString &path)
Sets the path used for storing settings for the given format and scope, to path.
Definition: qsettings.cpp:3578

◆ setValue()

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.

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

Example:

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

Definition at line 3328 of file qsettings.cpp.

Referenced by beginWriteArray(), QLocalServerPrivate::closeServer(), endArray(), QLibraryPrivate::isPlugin(), QLocalServerPrivate::listen(), qmlsqldatabase_change_version(), qmlsqldatabase_open_sync(), QFactoryLoader::updateDir(), QColorDialog::~QColorDialog(), QFileDialog::~QFileDialog(), and QScriptEngineDebuggerPrivate::~QScriptEngineDebuggerPrivate().

3329 {
3330  Q_D(QSettings);
3331  QString k = d->actualKey(key);
3332  d->set(k, value);
3333  d->requestUpdate();
3334 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482

◆ status()

QSettings::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()

Definition at line 3041 of file qsettings.cpp.

3042 {
3043  Q_D(const QSettings);
3044  return d->status;
3045 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ 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 function is called automatically from QSettings's destructor and by the event loop at regular intervals, so you normally don't need to call it yourself.

See also
status()

Definition at line 2882 of file qsettings.cpp.

2883 {
2884  Q_D(QSettings);
2885  d->sync();
2886 }
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
#define Q_D(Class)
Definition: qglobal.h:2482

◆ value()

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

Returns the value for setting key.

If the setting doesn't exist, returns defaultValue.

If no default value is specified, a default QVariant 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 the Section and Key Syntax rules.

Example:

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

Definition at line 3460 of file qsettings.cpp.

Referenced by allowsMessages(), beginReadArray(), QLocalSocket::connectToServer(), fontNameSubstitute(), fontPath(), QColorDialogPrivate::init(), QFileDialogPrivate::init(), QLibraryPrivate::isPlugin(), kdeColor(), QKde::kdeStyle(), QKde::kdeToolBarIconSize(), QKde::kdeToolButtonStyle(), QLibraryInfo::location(), qmlsqldatabase_open_sync(), QMultiInputContext::QMultiInputContext(), QPSPrintEnginePrivate::QPSPrintEnginePrivate(), qt_applyFontDatabaseSettings(), QApplicationPrivate::qt_mac_apply_settings(), qt_mac_update_os_settings(), MetaObjectGenerator::readClassInfo(), MetaObjectGenerator::readEventInfo(), MetaObjectGenerator::readInterfaceInfo(), QAxBase::setControl(), QApplication::setDoubleClickInterval(), QScriptEngineDebugger::standardWindow(), QGuiPlatformPlugin::systemIconThemeName(), QFactoryLoader::updateDir(), and QApplicationPrivate::x11_apply_settings().

3461 {
3462  Q_D(const QSettings);
3463  QVariant result = defaultValue;
3464  QString k = d->actualKey(key);
3465  d->get(k, &result);
3466  return result;
3467 }
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
double d
Definition: qnumeric_p.h:62
The QSettings class provides persistent platform-independent application settings.
Definition: qsettings.h:73
The QString class provides a Unicode character string.
Definition: qstring.h:83
#define Q_D(Class)
Definition: qglobal.h:2482

The documentation for this class was generated from the following files: