QSettings Class Reference
|
Locations | obj1 | obj2 | obj3 | obj4 |
---|---|---|---|---|
1. User, Application | X | |||
2. User, Organization | o | X | ||
3. System, Application | o | X | ||
4. System, Organization | o | o | o | X |
The beauty of this mechanism is that it works on all platforms supported by Qt and that it still gives you a lot of flexibility, without requiring you to specify any file names or registry paths.
If you want to use INI files on all platforms instead of the native API, you can pass QSettings::IniFormat as the first argument to the QSettings constructor, followed by the scope, the organization name, and the application name:
QSettings settings(QSettings::IniFormat, QSettings::UserScope, "MySoft", "Star Runner");
The Settings 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 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.
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. Changes performed by another process aren't visible in the current process until sync() is called.
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:
On Mac OS X versions 10.2 and 10.3, these files are used by default:
On Windows, NativeFormat settings are stored in the following registry paths:
Note: On Windows, for 32-bit programs running in WOW64 mode, settings are stored in the following registry path: HKEY_LOCAL_MACHINE\Software\WOW6432node.
If the file format is IniFormat, the following files are used on Unix and Mac OS X:
On Windows, the following files are used:
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.
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 by setting the XDG_CONFIG_HOME environment variable; see setPath() 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 the QSettings constructor that takes a file name as first argument and pass QSettings::IniFormat as second argument. Например:
QSettings settings("/home/petra/misc/myapp.ini", QSettings::IniFormat);
You can then use the QSettings object to read and write settings in the file.
On Mac OS X, you can access XML-based .plist files by passing QSettings::NativeFormat as second argument. Например:
QSettings settings("/Users/petra/misc/myapp.plist", QSettings::NativeFormat);
On Windows, QSettings lets you access settings that have been written with QSettings (or settings in a supported format, e.g., string data) in the system registry. This is done by constructing a QSettings object with a path in the registry and QSettings::NativeFormat.
Например:
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Office", QSettings::NativeFormat);
All the registry entries that appear under the specified path can be read or written through the QSettings object as usual (using forward slashes instead of backslashes). Например:
settings.setValue("11.0/Outlook/Security/DontTrustInstalledFiles", 0);
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.
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.
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:
#ifdef Q_WS_MAC QSettings settings("grenoullelogique.fr", "Squash"); #else QSettings settings("Grenoulle Logique", "Squash"); #endif
See also QVariant, QSessionManager, Settings Editor Example, and Application Example.
This enum type specifies the storage format used by QSettings.
Константа | Значение | Описание |
---|---|---|
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 by registerFormat(). |
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:
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.
windir = C:\Windows
QSettings always treats backslash as a special character and provides no API for reading or writing such entries.
See also registerFormat() and setPath().
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 and registerFormat().
This enum specifies whether settings are user-specific or shared by all users of the same system.
Константа | Значение | Описание |
---|---|---|
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. |
Смотрите также setPath().
Typedef for QMap<QString, QVariant>.
See also registerFormat().
The following status values are possible:
Константа | Значение | Описание |
---|---|---|
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 also status().
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 and registerFormat().
Constructs a QSettings object for accessing settings of the application called application from the organization called organization, and with parent parent.
Пример:
QSettings settings("Moose Tech", "Facturo-Pro");
The scope is QSettings::UserScope and the format is QSettings::NativeFormat.
See also setDefaultFormat() and Fallback Mechanism.
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 QSettings::NativeFormat.
If no application name is given, the QSettings object will only access the organization-wide locations.
See also setDefaultFormat().
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 locations.
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:
See also fileName().
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).
The code
QSettings settings("Moose Soft", "Facturo-Pro");
is equivalent to
QCoreApplication::setOrganizationName("Moose Soft"); QCoreApplication::setApplicationName("Facturo-Pro"); QSettings settings;
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(), and setDefaultFormat().
Destroys the QSettings object.
Any unsaved changes will eventually be written to permanent storage.
See also sync().
Returns a list of all keys, including subkeys, that can be read using the QSettings object.
Пример:
QSettings settings;
settings.setValue("fridge/color", Qt::white);
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", true);
settings.setValue("tv", false);
QStringList keys = settings.allKeys();
// keys: ["fridge/color", "fridge/size", "sofa", "tv"]
If a group is set using beginGroup(), only the keys in the group are returned, without the group prefix:
settings.beginGroup("fridge");
keys = settings.allKeys();
// keys: ["color", "size"]
See also childGroups() and childKeys().
Returns the application name used for storing the settings.
Эта функция была введена в Qt 4.4.
See also QCoreApplication::applicationName(), format(), scope(), and organizationName().
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. Например:
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:
Call endGroup() to reset the current group to what it was before the corresponding beginGroup() call. Groups can be nested.
See also endGroup() and group().
Adds prefix to the current group and starts reading from an array. Returns the size of the array.
Пример:
struct Login { QString userName; QString password; }; QList<Login> logins; ... QSettings settings; int size = settings.beginReadArray("logins"); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); Login login; login.userName = settings.value("userName").toString(); login.password = settings.value("password").toString(); logins.append(login); } settings.endArray();
Use beginWriteArray() to write the array in the first place.
See also beginWriteArray(), endArray(), and setArrayIndex().
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
To read back an array, use beginReadArray().
See also beginReadArray(), endArray(), and setArrayIndex().
Returns a list of all key top-level groups that contain keys that can be read using the QSettings object.
Пример:
QSettings settings;
settings.setValue("fridge/color", Qt::white);
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", true);
settings.setValue("tv", false);
QStringList groups = settings.childGroups();
// group: ["fridge"]
If a group is set using beginGroup(), the first-level keys in that group are returned, without the group prefix.
settings.beginGroup("fridge");
groups = settings.childGroups();
// groups: []
You can navigate through the entire setting hierarchy using childKeys() and childGroups() recursively.
See also childKeys() and allKeys().
Returns a list of all top-level keys that can be read using the QSettings object.
Пример:
QSettings settings;
settings.setValue("fridge/color", Qt::white);
settings.setValue("fridge/size", QSize(32, 96));
settings.setValue("sofa", true);
settings.setValue("tv", false);
QStringList keys = settings.childKeys();
// keys: ["sofa", "tv"]
If a group is set using beginGroup(), the top-level keys in that group are returned, without the group prefix:
settings.beginGroup("fridge");
keys = settings.childKeys();
// keys: ["color", "size"]
You can navigate through the entire setting hierarchy using childKeys() and childGroups() recursively.
See also childGroups() and allKeys().
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() and setFallbacksEnabled().
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 Key Syntax rules.
See also value() and setValue().
Returns default file format used for storing settings for the QSettings(QObject *) constructor. If no default format is set, QSettings::NativeFormat is used.
Эта функция была введена в Qt 4.4.
See also setDefaultFormat() and format().
Closes the array that was started using beginReadArray() or beginWriteArray().
See also beginReadArray() and beginWriteArray().
Resets the group to what it was before the corresponding beginGroup() call.
Пример:
settings.beginGroup("alpha"); // settings.group() == "alpha" settings.beginGroup("beta"); // settings.group() == "alpha/beta" settings.endGroup(); // settings.group() == "alpha" settings.endGroup(); // settings.group() == ""
See also beginGroup() and group().
Returns true if fallbacks are enabled; returns false otherwise.
By default, fallbacks are enabled.
See also setFallbacksEnabled().
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() and format().
Returns the format used for storing the settings.
Эта функция была введена в Qt 4.4.
See also defaultFormat(), fileName(), scope(), organizationName(), and applicationName().
Returns the current group.
See also beginGroup() and endGroup().
Returns the codec that is used for accessing INI files. By default, no codec is used, so a null pointer is returned.
Эта функция была введена в Qt 4.5.
See also setIniCodec().
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(), and sync().
Returns the organization name used for storing the settings.
Эта функция была введена в Qt 4.4.
See also QCoreApplication::organizationName(), format(), scope(), and applicationName().
Registers a custom storage format. On success, returns a special Format value that can then be passed to the QSettings constuctor. 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.
Пример:
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::UserSettings, "MySoft", "Star Runner"); ... }
Замечание: Эта функция потокобезопасна.
Эта функция была введена в Qt 4.1.
Смотрите также setPath().
Removes the setting key and any sub-settings of key.
Пример:
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. Например:
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 Key Syntax rules.
See also setValue(), value(), and contains().
Returns the scope used for storing the settings.
Эта функция была введена в Qt 4.4.
See also format(), organizationName(), and applicationName().
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.
Sets the default file format to the given format, used for storing settings for the QSettings(QObject *) constructor.
If no default format is set, QSettings::NativeFormat is used.
Эта функция была введена в Qt 4.4.
See also defaultFormat() and format().
Sets whether fallbacks are enabled to b.
By default, fallbacks are enabled.
See also fallbacksEnabled().
Sets the codec for accessing INI files (including .conf files on Unix) to codec. The codec is used for decoding any data that is read from the INI file, and for encoding any data that is written to the file. By default, no codec is used, and non-ASCII characters are encoded using standard INI escape sequences.
Warning: The codec must be set immediately after creating the QSettings object, before accessing any data.
Эта функция была введена в Qt 4.5.
See also iniCodec().
Это перегруженная функция.
Sets the codec for accessing INI files (including .conf files on Unix) to the QTextCodec for the encoding specified by codecName. Common values for codecName include "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't recognized, nothing happens.
Эта функция была введена в Qt 4.5.
See also QTextCodec::codecForName().
Sets the path used for storing settings for the given format and scope, to path. The format can be a custom format.
The table below summarizes the default values:
Платформа | Формат | Scope | Path |
---|---|---|---|
Windows | IniFormat | UserScope | %APPDATA% |
SystemScope | %COMMON_APPDATA% | ||
Unix | NativeFormat, IniFormat | UserScope | $HOME/.config |
SystemScope | /etc/xdg | ||
Qt для встраиваемых Linux-систем | NativeFormat, IniFormat | UserScope | $HOME/Settings |
SystemScope | /etc/xdg | ||
Mac OS X | IniFormat | UserScope | $HOME/.config |
SystemScope | /etc/xdg |
The default UserScope paths on Unix and Mac OS X ($HOME/.config or $HOME/Settings) can be overridden by the user by setting the XDG_CONFIG_HOME environment variable. 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.
Эта функция была введена в Qt 4.1.
See also registerFormat().
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 Key Syntax rules.
Пример:
QSettings settings; settings.setValue("interval", 30); settings.value("interval").toInt(); // returns 30 settings.setValue("interval", 6.55); settings.value("interval").toDouble(); // returns 6.55
See also value(), remove(), and contains().
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().
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().
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 Key Syntax rules.
Пример:
QSettings settings; settings.setValue("animal/snake", 58); settings.value("animal/snake", 1024).toInt(); // returns 58 settings.value("animal/zebra", 1024).toInt(); // returns 1024 settings.value("animal/zebra").toInt(); // returns 0
See also setValue(), contains(), and remove().
Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) | Торговые марки | Qt 4.5.3 |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |