The QSettings class provides persistent platform-independent application settings. 更多...
| 頭: | #include <QSettings> |
| qmake: | QT += core |
| 繼承: | QObject |
注意: 此類的所有函數 可重入 .
注意: 這些函數也是 綫程安全 :
| enum | Format { NativeFormat, Registry32Format, Registry64Format, IniFormat, InvalidFormat } |
| typedef | ReadFunc |
| enum | Scope { UserScope, SystemScope } |
| typedef | SettingsMap |
| enum | Status { NoError, AccessError, FormatError } |
| typedef | WriteFunc |
| QSettings (const QString & organization , const QString & application = QString(), QObject * parent = nullptr) | |
| QSettings (QSettings::Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = nullptr) | |
| QSettings (QSettings::Format format , QSettings::Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = nullptr) | |
| QSettings (const QString & fileName , QSettings::Format format , QObject * parent = nullptr) | |
| QSettings (QObject * parent = nullptr) | |
| virtual | ~QSettings () |
| QStringList | allKeys () const |
| QString | applicationName () const |
| void | beginGroup (const QString & prefix ) |
| int | beginReadArray (const QString & prefix ) |
| void | beginWriteArray (const QString & prefix , int size = -1) |
| QStringList | childGroups () const |
| QStringList | childKeys () const |
| void | clear () |
| bool | contains (const QString & key ) const |
| void | endArray () |
| void | endGroup () |
| bool | fallbacksEnabled () const |
| QString | fileName () const |
| QSettings::Format | format () const |
| QString | group () const |
| QTextCodec * | iniCodec () const |
| bool | isAtomicSyncRequired () const |
| bool | isWritable () const |
| QString | organizationName () const |
| void | remove (const QString & key ) |
| QSettings::Scope | scope () const |
| void | setArrayIndex (int i ) |
| void | setAtomicSyncRequired (bool enable ) |
| void | setFallbacksEnabled (bool b ) |
| void | setIniCodec (QTextCodec * codec ) |
| void | setIniCodec (const char * codecName ) |
| void | setValue (const QString & key , const QVariant & value ) |
| QSettings::Status | status () const |
| void | sync () |
| QVariant | value (const QString & key , const QVariant & defaultValue = QVariant()) const |
| QSettings::Format | defaultFormat () |
| QSettings::Format | registerFormat (const QString & extension , QSettings::ReadFunc readFunc , QSettings::WriteFunc writeFunc , Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive) |
| void | setDefaultFormat (QSettings::Format format ) |
| void | setPath (QSettings::Format format , QSettings::Scope scope , const QString & path ) |
| const QMetaObject | staticMetaObject |
| virtual bool | event (QEvent * event ) override |
The QSettings class provides persistent platform-independent application settings.
Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in property list files on macOS and iOS. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.
QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports 自定義存儲格式 .
QSettings 's API is based on QVariant ,允許保存大多數基於值的類型,譬如 QString , QRect ,和 QImage ,采用最少努力。
若需要的全是基於內存的非持久性結構,請考慮使用 QMap < QString , QVariant > 代替。
當創建 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.
若使用 QSettings from many places in your application, you might want to specify the organization name and the application name using QCoreApplication::setOrganizationName () 和 QCoreApplication::setApplicationName (), and then use the default QSettings 構造函數:
QCoreApplication::setOrganizationName("MySoft");
QCoreApplication::setOrganizationDomain("mysoft.com");
QCoreApplication::setApplicationName("Star Runner");
...
QSettings settings;
(Here, we also specify the organization's Internet domain. When the Internet domain is set, it is used on macOS and iOS instead of the organization name, since macOS and iOS applications conventionally use Internet domains to identify themselves. If no domain is set, a fake domain is derived from the organization name. See the 特定平颱注意事項 瞭解細節)。
QSettings stores settings. Each setting consists of a QString 指定設置的名稱 ( key ) 和 QVariant 存儲鍵關聯數據。要寫入設置,使用 setValue ()。例如:
settings.setValue("editor/wrapMargin", 68);
若已經存在具有相同鍵的設置,則現有值被新值所覆寫。為提高效率,改變可能不會被立即保存到永久存儲。(可以始終調用 sync () 去提交改變。)
可以獲取設置的值使用 value ():
int margin = settings.value("editor/wrapMargin").toInt();
If there is no setting with the specified name, QSettings returns a null QVariant (其可以被轉換成整數 0)。可以指定另一默認值通過把第 2 自變量傳遞給 value ():
int margin = settings.value("editor/wrapMargin", 80).toInt();
要測試給定鍵是否存在,調用 contains ()。要移除鍵關聯設置,調用 remove ()。要獲得所有鍵的列錶,調用 allKeys ()。要移除所有鍵,調用 clear ().
因為
QVariant
屬於 Qt Core 模塊,它不能提供數據類型轉換函數,如
QColor
,
QImage
,和
QPixmap
,其屬於 Qt GUI。換句話說,沒有
toColor()
,
toImage()
,或
toPixmap()
函數在
QVariant
.
取而代之,可以使用 QVariant::value () or the qVariantValue() template function. For example:
QSettings settings("MySoft", "Star Runner"); QColor color = settings.value("DataPump/bgcolor").value<QColor>();
反嚮轉換 (如,從 QColor to QVariant ) 對於所有支持數據類型是自動通過 QVariant ,包括 GUI 相關類型:
QSettings settings("MySoft", "Star Runner"); QColor color = palette().background().color(); settings.setValue("DataPump/bgcolor", color);
自定義類型注冊采用 qRegisterMetaType () 和 qRegisterMetaTypeStreamOperators () can be stored using QSettings .
Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, follow these simple rules:
可以使用 / 字符作為分隔符來形成分層鍵,類似 Unix 文件路徑。例如:
settings.setValue("mainwindow/size", win->size());
settings.setValue("mainwindow/fullScreen", win->isFullScreen());
settings.setValue("outputpanel/visible", panel->isVisible());
若希望保存 (或還原) 許多采用相同前綴的設置,可以指定前綴使用 beginGroup () 和調用 endGroup () 在末尾。這裏又是相同範例,但此次使用組機製:
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();
若組的設置是使用 beginGroup (),因此,大多數函數的行為改變。組可以被遞歸設置。
In addition to groups, QSettings also supports an "array" concept. See beginReadArray () 和 beginWriteArray () 瞭解細節。
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:
(見 特定平颱注意事項 瞭解在 Qt 支持的不同平颱,這些位置的有關信息)。
若在第一位置找不到鍵,則在第二位置繼續搜索,依此類推。這使您能夠存儲係統範圍 (或組織範圍) 設置,並在每用戶 (或每應用程序) 的基礎上覆蓋它們。要關閉此機製,調用 setFallbacksEnabled (false).
雖然來自所有 4 個位置的鍵都可用於讀取,但僅第 1 個文件 (為手中應用程序的特定用戶位置) 可寫訪問。要寫入任何其它文件,省略應用程序名稱和/或指定 QSettings::SystemScope (而不是 QSettings::UserScope ,默認)。
讓我們看下範例:
QSettings obj1("MySoft", "Star Runner");
QSettings obj2("MySoft");
QSettings obj3(QSettings::SystemScope, "MySoft", "Star Runner");
QSettings obj4(QSettings::SystemScope, "MySoft");
The table below summarizes which QSettings objects access which location. " X " means that the location is the main location associated to the QSettings object and is used both for reading and for writing; "o" means that the location is used as a fallback when reading.
| 位置 |
obj1
|
obj2
|
obj3
|
obj4
|
|---|---|---|---|---|
| 1. 用戶、應用程序 | X | |||
| 2. 用戶、組織 | o | X | ||
| 3. 係統、應用程序 | o | X | ||
| 4. 係統、組織 | o | o | o | X |
這種機製的妙處是它工作於由 Qt 支持的所有平颱,且仍然給予很大靈活性,不要求指定任何文件名 (或注冊錶路徑)。
若想要在所有平颱使用 INI 文件而不是本機 API,可以傳遞 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");
注意:不預留類型信息,當從 INI 文件讀取設置時;所有值將返迴作為 QString .
The 設置編輯器 範例允許您試驗不同設置位置,及啓用或禁用迴退。
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(); }
見 窗口幾何體 瞭解為什麼更好的論述,調用 QWidget::resize () 和 QWidget::move () 而不是 QWidget::setGeometry () 去還原窗口幾何體。
The
readSettings()
and
writeSettings()
函數必須從主窗口的構造函數調用,關閉事件處理程序如下所示:
MainWindow::MainWindow() { ... readSettings(); } void MainWindow::closeEvent(QCloseEvent *event) { if (userReallyWantsToQuit()) { writeSettings(); event->accept(); } else { event->ignore(); } }
見 Application example for a self-contained example that uses QSettings .
QSettings is 可重入 . This means that you can use distinct QSettings object in different threads simultaneously. This guarantee stands even when the QSettings objects refer to the same files on disk (or to the same entries in the system registry). If a setting is modified through one QSettings object, the change will immediately be visible in any other QSettings objects that operate on the same location and that live in the same process.
QSettings can safely be used from different processes (which can be different instances of your application running at the same time or different applications altogether) to read and write to the same system locations, provided certain conditions are met. For QSettings::IniFormat ,它使用諮詢文件鎖定和智能閤並算法,以確保數據的完整性。工作條件是可寫配置文件必須為常規文件,且必須位於當前用戶可以在其中創建新臨時文件的目錄下。若不是這種情況,就必須使用 setAtomicSyncRequired () 關閉安全性。
注意, sync () imports changes made by other processes (in addition to writing the changes from this QSettings ).
如提及在 迴退機製 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.
在 Unix 係統,若文件格式為 NativeFormat ,默認使用下列文件:
$HOME/.config/MySoft/Star Runner.conf
(Qt for Embedded Linux:
$HOME/Settings/MySoft/Star Runner.conf
)
$HOME/.config/MySoft.conf
(Qt for Embedded Linux:
$HOME/Settings/MySoft.conf
)
<dir>/MySoft/Star Runner.conf
<dir>/MySoft.conf
注意:
若 XDG_CONFIG_DIRS 未設置,默認值
/etc/xdg
被使用。
On macOS versions 10.2 and 10.3, these files are used by default:
$HOME/Library/Preferences/com.MySoft.Star Runner.plist
$HOME/Library/Preferences/com.MySoft.plist
/Library/Preferences/com.MySoft.Star Runner.plist
/Library/Preferences/com.MySoft.plist
在 Windows, NativeFormat 設置存儲在下列注冊錶路徑:
HKEY_CURRENT_USER\Software\MySoft\Star Runner
HKEY_CURRENT_USER\Software\MySoft\OrganizationDefaults
HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
HKEY_LOCAL_MACHINE\Software\MySoft\OrganizationDefaults
注意:
在 Windows,對於運行在 WOW64 模式下的 32 位程序,設置存儲在下列注冊錶路徑:
HKEY_LOCAL_MACHINE\Software\WOW6432node
.
若文件格式為 NativeFormat ,這是 Settings/MySoft/Star Runner.conf 在應用程序 Home (主) 目錄。
若文件格式為 IniFormat , the following files are used on Unix, macOS , and iOS:
$HOME/.config/MySoft/Star Runner.ini
(Qt for Embedded Linux:
$HOME/Settings/MySoft/Star Runner.ini
)
$HOME/.config/MySoft.ini
(Qt for Embedded Linux:
$HOME/Settings/MySoft.ini
)
<dir>/MySoft/Star Runner.ini
<dir>/MySoft.ini
注意:
若 XDG_CONFIG_DIRS 未設置,默認值
/etc/xdg
被使用。
在 Windows,使用下列文件:
FOLDERID_RoamingAppData\MySoft\Star Runner.ini
FOLDERID_RoamingAppData\MySoft.ini
FOLDERID_ProgramData\MySoft\Star Runner.ini
FOLDERID_ProgramData\MySoft.ini
標識符加前綴通過
FOLDERID_
是要被傳遞給 Win32 API 函數的特殊項 ID 列錶
SHGetKnownFolderPath()
以獲取相應路徑。
FOLDERID_RoamingAppData
通常指嚮
C:\Users\User Name\AppData\Roaming
,也可展示通過環境變量
%APPDATA%
.
FOLDERID_ProgramData
通常指嚮
C:\ProgramData
.
若文件格式為 IniFormat ,這是 Settings/MySoft/Star Runner.ini 在應用程序 Home (主) 目錄。
路徑對於
.ini
and
.conf
文件可以改變使用
setPath
(). On Unix,
macOS
, and iOS the user can override them by setting the
XDG_CONFIG_HOME
環境變量;見
setPath
() 瞭解細節。
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 作為第 2 自變量。例如:
QSettings settings("/home/petra/misc/myapp.ini", QSettings::IniFormat);
You can then use the QSettings object to read and write settings in the file.
On
macOS
and iOS, you can access property list
.plist
文件通過傳遞
QSettings::NativeFormat
作為第 2 自變量。例如:
QSettings settings("/Users/petra/misc/myapp.plist", QSettings::NativeFormat);
在 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). 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.
在 Windows,鍵有值和子鍵兩者是可能的。通過使用 Default 或 . 代替子鍵訪問其默認值:
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"
在 Windows 外的其它平颱,Default 和 . 將被視為常規子鍵。
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:
REG_EXPAND_SZ
將改變為
REG_SZ
.
main()
function and then use the default
QSettings
constructor. Another solution is to use preprocessor directives, for example:
#ifdef Q_OS_MAC QSettings settings( "grenoullelogique.fr" , "Squash" ); #else QSettings settings( "Grenoulle Logique" , "Squash" ); #endif
另請參閱 QVariant , QSessionManager , 設置編輯器範例 ,和 應用程序範例 .
此枚舉類型指定存儲格式,用於 QSettings .
| 常量 | 值 | 描述 |
|---|---|---|
QSettings::NativeFormat
|
0
|
Store the settings using the most appropriate storage format for the platform. On Windows, this means the system registry; on macOS and iOS, this means the CFPreferences API; on Unix, this means textual configuration files in INI format. |
QSettings::Registry32Format
|
2
|
僅 Windows:從 64 位 Windows 運行 64 位應用程序明確訪問 32 位係統注冊錶。在 32 位 Windows 或從 64 位 Windows 運行 32 位應用程序,這的工作如同指定 NativeFormat。該枚舉值在 Qt 5.7 添加。 |
QSettings::Registry64Format
|
3
|
僅 Windows:從 64 位 Windows 運行 32 位應用程序明確訪問 64 位係統注冊錶。在 32 位 Windows 或從 64 位 Windows 運行 64 位應用程序,這的工作如同指定 NativeFormat。該枚舉值在 Qt 5.7 添加。 |
QSettings::IniFormat
|
1
|
把設置存儲在 INI 文件中。注意,不預留類型信息,當從 INI 文件讀取設置時;所有值將被返迴作為 QString . |
QSettings::InvalidFormat
|
16
|
特殊值的返迴通過 registerFormat (). |
在 Unix,NativeFormat 和 IniFormat 意味著相同事情,除文件擴展名不同外 (
.conf
為 NativeFormat,
.ini
為 IniFormat)。
INI 文件格式是在所有平颱 Qt 所支持的 Windows 文件格式。在缺乏 INI 標準的情況下,我們試著遵循 Microsoft 做法,但有以下例外:
@
基句法以編碼類型。例如:
pos = @Point(100 100)
為最小化兼容性問題,任何
@
未齣現在值第一位置或之後未緊跟 Qt 類型 (
點
,
Rect
,
Size
,等) 被視為正常字符。
\
) 在文件路徑:
windir = C:\Windows
QSettings 始終視反斜杠為特殊字符,且不提供用於讀取或寫入這種條目的 API。
%
作為鍵中轉義字符。此外,若保存頂層設置 (其中不帶斜綫的鍵,如 someKey),它將齣現在 INI 文件的 General 區間。為避免覆蓋其它鍵,若使用如 General/someKey 的這種鍵保存某些事情,鍵將位於 %General 區間,
not
在 General 區間。
另請參閱 registerFormat () 和 setPath ().
typedef 為指嚮采用以下簽名的函數指針:
bool myReadFunc(QIODevice &device, QSettings::SettingsMap &map);
ReadFunc
用於
registerFormat()
作為指嚮讀取一組鍵/值對的函數指針。
ReadFunc
應一次性讀取所有選項,並返迴所有設置在
SettingsMap
容器,其最初為空。
另請參閱 WriteFunc and registerFormat ().
此枚舉指定設置是具體用戶,還是由同一係統的所有用戶共享。
| 常量 | 值 | 描述 |
|---|---|---|
QSettings::UserScope
|
0
|
將設置存儲到當前用戶的特定位置 (如:用戶 Home 主目錄)。 |
QSettings::SystemScope
|
1
|
將設置存儲在全局位置,以便同一計算機中的所有用戶訪問相同設置集。 |
另請參閱 setPath ().
typedef 對於 QMap < QString , QVariant >.
另請參閱 registerFormat ().
下列狀態值是可能的:
| 常量 | 值 | 描述 |
|---|---|---|
QSettings::NoError
|
0
|
沒有齣現錯誤。 |
QSettings::AccessError
|
1
|
發生訪問錯誤 (如:試著寫入隻讀文件)。 |
QSettings::FormatError
|
2
|
發生格式錯誤 (如:加載畸形 INI 文件)。 |
另請參閱 status ().
typedef 為指嚮采用以下簽名的函數指針:
bool myWriteFunc(QIODevice &device, const QSettings::SettingsMap &map);
WriteFunc
用於
registerFormat()
作為指嚮寫入一組鍵/值對的函數指針。
WriteFunc
僅調用一次,所以需要一次性輸齣設置。
另請參閱 ReadFunc and registerFormat ().
構造 QSettings object for accessing settings of the application called application 從組織稱為 organization ,和采用父級 parent .
範例:
QSettings settings("Moose Tech", "Facturo-Pro");
作用域設置為 QSettings::UserScope ,和格式設置為 QSettings::NativeFormat (即:調用 setDefaultFormat () 在調用此構造函數不起作用之前)。
另請參閱 setDefaultFormat () 和 迴退機製 .
構造 QSettings object for accessing settings of the application called application 從組織稱為 organization ,和采用父級 parent .
若 scope is QSettings::UserScope , QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope , QSettings object ignores user-specific settings and provides access to system-wide settings.
存儲格式被設為 QSettings::NativeFormat (即:調用 setDefaultFormat () 在調用此構造函數不起作用之前)。
If no application name is given, the QSettings object will only access the organization-wide locations .
另請參閱 setDefaultFormat ().
構造 QSettings object for accessing settings of the application called application 從組織稱為 organization ,和采用父級 parent .
若 scope is QSettings::UserScope , QSettings object searches user-specific settings first, before it searches system-wide settings as a fallback. If scope is QSettings::SystemScope , QSettings object ignores user-specific settings and provides access to system-wide settings.
若 format is QSettings::NativeFormat ,本機 API 用於存儲設置。若 format is QSettings::IniFormat ,使用 INI 格式。
If no application name is given, the QSettings object will only access the organization-wide locations .
構造 QSettings object for accessing the settings stored in the file called fileName ,采用父級 parent 。若文件不存在,創建它。
若
format
is
QSettings::NativeFormat
,含義對於
fileName
從屬平颱。在 Unix,
fileName
is the name of an INI file. On
macOS
and iOS,
fileName
是名稱對於
.plist
文件。在 Windows,
fileName
是係統注冊錶路徑。
若 format is QSettings::IniFormat , fileName 是 INI 文件的名稱。
警告:
提供此函數是為瞭方便。它能很好地訪問 INI 或
.plist
文件生成通過 Qt,但可能失敗當在發源於其它程序的這種文件中發現某些句法時。尤其,要意識到以下局限性:
@
字符作某些上下文元字符,以編碼 Qt 特定數據類型 (如
@Rect
),因此,可能被誤解當它齣現在純 INI 文件中時。
另請參閱 fileName ().
構造 QSettings object for accessing settings of the application and organization set previously with a call to QCoreApplication::setOrganizationName (), QCoreApplication::setOrganizationDomain (),和 QCoreApplication::setApplicationName ().
作用域是 QSettings::UserScope 和格式為 defaultFormat () ( QSettings::NativeFormat 默認情況下)。使用 setDefaultFormat () 在調用此構造函數之前去更改用於此構造函數的默認格式。
代碼
QSettings settings("Moose Soft", "Facturo-Pro");
相當於
QCoreApplication::setOrganizationName("Moose Soft"); QCoreApplication::setApplicationName("Facturo-Pro"); QSettings settings;
若 QCoreApplication::setOrganizationName () 和 QCoreApplication::setApplicationName () has not been previously called, the QSettings object will not be able to read or write any settings, and status () 會返迴 AccessError .
On macOS and iOS, 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.
另請參閱 QCoreApplication::setOrganizationName (), QCoreApplication::setOrganizationDomain (), QCoreApplication::setApplicationName (),和 setDefaultFormat ().
[虛擬]
QSettings::
~QSettings
()
銷毀 QSettings 對象。
任何未保存的改變最後被寫入永久存儲。
另請參閱 sync ().
返迴所有鍵的列錶 (包括子鍵),可以被讀取使用 QSettings 對象。
範例:
QSettings settings; settings.setValue("fridge/color", QColor(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"]
若組的設置是使用 beginGroup (),僅返迴組中的鍵,不帶組前綴:
settings.beginGroup("fridge"); keys = settings.allKeys(); // keys: ["color", "size"]
另請參閱 childGroups () 和 childKeys ().
返迴用於存儲設置的應用程序名稱。
該函數在 Qt 4.4 引入。
另請參閱 QCoreApplication::applicationName (), format (), scope (),和 organizationName ().
追加 prefix 到當前組。
當前組自動前置所有指定鍵到 QSettings 。此外,查詢函數譬如 childGroups (), childKeys (),和 allKeys () 都是基於組的。默認情況下,未設置組。
組對避免一遍又一遍地鍵入相同設置路徑很有用。例如:
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();
這將設置 3 個設置值:
mainwindow/size
mainwindow/fullScreen
outputpanel/visible
調用 endGroup () 以將當前組重置到調用相應 beginGroup() 之前的狀態。組可以嵌套。
添加 prefix 到當前組並從數組開始讀取。返迴數組的大小。
範例:
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();
使用 beginWriteArray () 以首先寫入數組。
另請參閱 beginWriteArray (), endArray (),和 setArrayIndex ().
添加 prefix 到當前組並開始寫入數組大小 size 。若 size 為 -1 (默認),它是基於所寫條目的索引自動確定的。
若某組鍵多次齣現,則可以使用數組來讓您的生活變得更輕鬆。例如,假設想要保存用戶名和口令的可變長度列錶。那麼可以寫:
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();
生成鍵將擁有形式
logins/size
logins/1/userName
logins/1/password
logins/2/userName
logins/2/password
logins/3/userName
logins/3/password
要讀迴數組,使用 beginReadArray ().
另請參閱 beginReadArray (), endArray (),和 setArrayIndex ().
返迴包含可讀取鍵的所有鍵頂層組的列錶,讀取使用 QSettings 對象。
範例:
QSettings settings; settings.setValue("fridge/color", QColor(Qt::white)); settings.setValue("fridge/size", QSize(32, 96)); settings.setValue("sofa", true); settings.setValue("tv", false); QStringList groups = settings.childGroups(); // groups: ["fridge"]
若組的設置是使用 beginGroup (),返迴該組中的首級鍵,不帶組前綴。
settings.beginGroup("fridge"); groups = settings.childGroups(); // groups: []
可以導航透過整個設置層次結構使用 childKeys () 和 childGroups() 遞歸。
另請參閱 childKeys () 和 allKeys ().
返迴所有頂層鍵的列錶,可以被讀取使用 QSettings 對象。
範例:
QSettings settings; settings.setValue("fridge/color", QColor(Qt::white)); settings.setValue("fridge/size", QSize(32, 96)); settings.setValue("sofa", true); settings.setValue("tv", false); QStringList keys = settings.childKeys(); // keys: ["sofa", "tv"]
若組的設置是使用 beginGroup (),僅返迴組中的頂層鍵,不帶組前綴:
settings.beginGroup("fridge"); keys = settings.childKeys(); // keys: ["color", "size"]
可以導航透過整個設置層次結構使用 childKeys() 和 childGroups () 遞歸。
另請參閱 childGroups () 和 allKeys ().
移除首要位置中的所有條目,關聯此 QSettings 對象。
不移除迴退位置條目。
若隻想移除的條目在當前 group (),使用 remove("") 代替。
另請參閱 remove () 和 setFallbacksEnabled ().
返迴
true
若存在設置被稱為
key
;否則返迴 false。
若組的設置是使用 beginGroup (), key 被認為是相對於該組的。
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the 區間和鍵句法 規則。
[static]
QSettings::Format
QSettings::
defaultFormat
()
返迴用於存儲設置的默認文件格式為 QSettings ( QObject *) 構造函數。若未設置默認格式, QSettings::NativeFormat 被使用。
該函數在 Qt 4.4 引入。
另請參閱 setDefaultFormat () 和 format ().
關閉已啓動數組使用 beginReadArray () 或 beginWriteArray ().
另請參閱 beginReadArray () 和 beginWriteArray ().
重置組狀態先前的相應 beginGroup () 調用。
範例:
settings.beginGroup("alpha"); // settings.group() == "alpha" settings.beginGroup("beta"); // settings.group() == "alpha/beta" settings.endGroup(); // settings.group() == "alpha" settings.endGroup(); // settings.group() == ""
另請參閱 beginGroup () 和 group ().
[override virtual protected]
bool
QSettings::
event
(
QEvent
*
event
)
重實現自 QObject::event ().
返迴
true
若迴退被啓用;返迴
false
否則。
默認情況下,迴退是啓用的。
另請參閱 setFallbacksEnabled ().
返迴寫入設置的路徑,使用此 QSettings 對象存儲。
在 Windows,若格式為 QSettings::NativeFormat ,返迴值是係統注冊錶路徑,而非文件路徑。
另請參閱 isWritable () 和 format ().
返迴用於存儲設置的格式。
該函數在 Qt 4.4 引入。
另請參閱 defaultFormat (), fileName (), scope (), organizationName (),和 applicationName ().
返迴當前組。
另請參閱 beginGroup () 和 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 引入。
另請參閱 setIniCodec ().
返迴
true
if
QSettings
隻允許履行設置的原子保存和重新加載 (同步)。返迴
false
若允許將設置內容直接保存到配置文件。
默認為
true
.
該函數在 Qt 5.10 引入。
另請參閱 setAtomicSyncRequired () 和 QSaveFile .
返迴
true
若設置可以寫入使用此
QSettings
對象;返迴
false
否則。
為什麼 isWritable() 可能返迴 false 的原因之一是若 QSettings 運轉於隻讀文件。
警告: 此函數並不完美可靠,因為文件權限可以隨時改變。
另請參閱 fileName (), status (),和 sync ().
返迴用於存儲設置的組織名稱。
該函數在 Qt 4.4 引入。
另請參閱 QCoreApplication::organizationName (), format (), scope (),和 applicationName ().
[static]
QSettings::Format
QSettings::
registerFormat
(const
QString
&
extension
,
QSettings::ReadFunc
readFunc
,
QSettings::WriteFunc
writeFunc
,
Qt::CaseSensitivity
caseSensitivity
= Qt::CaseSensitive)
注冊自定義存儲格式。當成功時,返迴特殊格式值,然後將其傳遞給 QSettings 構造函數。當故障時,返迴 InvalidFormat .
The extension 是關聯格式 (沒有 .) 的文件擴展名。
The readFunc and writeFunc 參數是指嚮讀寫一組鍵/值對的函數指針。 QIODevice 的讀寫函數參數始終以二進製方式被打開 (即,沒有 QIODevice::Text 標誌)。
The caseSensitivity 參數指定鍵是否區分大小寫。這會有所不同,當查找值使用 QSettings 。默認是區分大小寫的。
默認情況下,若使用就組織名稱和應用程序名稱而言工作的某一構造函數,則所用文件係統位置如同 IniFormat 。使用 setPath () 去指定其它位置。
範例:
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"); ... }
注意: 此函數是 綫程安全 .
該函數在 Qt 4.1 引入。
另請參閱 setPath ().
移除設置 key 和任何子設置為 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"]
注意,若某一迴退位置包含具有相同鍵的設置,在調用 remove() 後該設置將可見。
若 key 為空字符串,所有鍵在當前 group () 被移除。例如:
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 CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the 區間和鍵句法 規則。
另請參閱 setValue (), value (),和 contains ().
返迴用於存儲設置的作用域。
該函數在 Qt 4.4 引入。
另請參閱 format (), organizationName (),和 applicationName ().
將當前數組索引設為 i 。調用函數,譬如 setValue (), value (), remove (),和 contains () 將運轉於該索引數組條目。
必須調用 beginReadArray () 或 beginWriteArray () 在可以調用此函數之前。
配置是否
QSettings
要求履行設置的原子保存和重新加載 (同步)。若
enable
自變量為
true
(默認),
sync
() 隻會履行同步原子操作。若這不可能,
sync
() 會失敗且
status
() 將是錯誤條件。
把此特性設為
false
將允許
QSettings
直接寫入配置文件並忽略任何錯誤嘗試 (鎖定它阻止試著同時寫入的其它進程)。由於潛在破壞,應小心使用此選項,但在某些情況下是必需的,像
QSettings::IniFormat
配置文件 (存在於其它不可寫目錄下或 NTFS 備用數據流中)。
見 QSaveFile 瞭解有關特徵的更多信息。
該函數在 Qt 5.10 引入。
另請參閱 isAtomicSyncRequired () 和 QSaveFile .
[static]
void
QSettings::
setDefaultFormat
(
QSettings::Format
format
)
將默認文件格式設為給定 format ,用於存儲設置為 QSettings ( QObject *) 構造函數。
若未設置默認格式, QSettings::NativeFormat 被使用。見文檔編製瞭解 QSettings 構造函數,查看構造函數是否會忽略此函數。
該函數在 Qt 4.4 引入。
另請參閱 defaultFormat () 和 format ().
把是否啓用迴退設為 b .
默認情況下,迴退是啓用的。
另請參閱 fallbacksEnabled ().
設置訪問 INI 文件的編解碼器 (包括
.conf
文件在 Unix) 到
codec
。編解碼器被用於解碼從 INI 文件讀取的任何數據,和對寫入文件的任何數據進行編碼。默認情況下,不使用編解碼器,和使用標準 INI 轉義序列編碼非 ASCII 字符。
警告: 之後必須立即設置編解碼器當創建 QSettings 對象,在訪問任何數據之前。
該函數在 Qt 4.5 引入。
另請參閱 iniCodec ().
這是重載函數。
設置訪問 INI 文件的編解碼器 (包括
.conf
文件在 Unix) 到
QTextCodec
為指定編碼通過
codecName
。常見值對於
codecName
包括 ISO 8859-1、UTF-8 及 UTF-16。若編碼無法識彆,則什麼都不發生。
該函數在 Qt 4.5 引入。
另請參閱 QTextCodec::codecForName ().
[static]
void
QSettings::
setPath
(
QSettings::Format
format
,
QSettings::Scope
scope
, const
QString
&
path
)
設置用於存儲設置的路徑為給定 format and scope ,到 path 。 format 可以是自定義格式。
下錶匯總瞭默認值:
| 平颱 | 格式 | 作用域 | 路徑 |
|---|---|---|---|
| Windows | IniFormat | UserScope |
FOLDERID_RoamingAppData
|
| SystemScope |
FOLDERID_ProgramData
|
||
| Unix | NativeFormat , IniFormat | UserScope |
$HOME/.config
|
| SystemScope |
/etc/xdg
|
||
| Qt for Embedded Linux | NativeFormat , IniFormat | UserScope |
$HOME/Settings
|
| SystemScope |
/etc/xdg
|
||
| macOS and iOS | IniFormat | UserScope |
$HOME/.config
|
| SystemScope |
/etc/xdg
|
默認
UserScope
paths on Unix,
macOS
, and iOS (
$HOME/.config
或 $HOME/Settings) 可以由用戶覆蓋通過設置
XDG_CONFIG_HOME
環境變量。默認
SystemScope
paths on Unix,
macOS
, and iOS (
/etc/xdg
) 可以被覆蓋當構建 Qt 庫使用
configure
腳本的
-sysconfdir
標誌 (見
QLibraryInfo
瞭解細節)。
設置 NativeFormat paths on Windows, macOS , and iOS has no effect.
警告: 此函數不影響現有 QSettings 對象。
該函數在 Qt 4.1 引入。
另請參閱 registerFormat ().
設置值為設置 key to value 。若 key 已存在,先前值被覆寫。
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the 區間和鍵句法 規則。
範例:
QSettings settings; settings.setValue("interval", 30); settings.value("interval").toInt(); // returns 30 settings.setValue("interval", 6.55); settings.value("interval").toDouble(); // returns 6.55
另請參閱 value (), remove (),和 contains ().
返迴狀態碼指示遇到的首個錯誤通過 QSettings ,或 QSettings::NoError 若沒有齣現錯誤。
要意識到, QSettings 延遲履行某些操作。齣於此原因,可能想要調用 sync () 以確保數據存儲在 QSettings 被寫入磁盤在調用 status() 之前。
另請參閱 sync ().
把任何未保存改變寫入永久存儲,並重新加載同時已被另一應用程序改變的任何設置。
此函數被自動調用從 QSettings 的析構函數和通過定期間隔的事件循環,因此,通常不需要自己調用它。
另請參閱 status ().
返迴值為設置 key 。若設置不存在,返迴 defaultValue .
若未指定默認值,默認 QVariant 被返迴。
Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on macOS and iOS uses case-sensitive keys. To avoid portability problems, see the 區間和鍵句法 規則。
範例:
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