QSettings 類

The QSettings class provides persistent platform-independent application settings. 更多...

頭: #include <QSettings>
qmake: QT += core
繼承: QObject

注意: 此類的所有函數 可重入 .

注意: 這些函數也是 綫程安全 :

  • registerFormat (const QString &extension, ReadFunc readFunc, WriteFunc writeFunc, Qt::CaseSensitivity caseSensitivity)

公共類型

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 = Q_NULLPTR)
QSettings (Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)
QSettings (Format format , Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)
QSettings (const QString & fileName , Format format , QObject * parent = Q_NULLPTR)
QSettings (QObject * parent = Q_NULLPTR)
~QSettings ()
QStringList allKeys () const
QString applicationName () const
void beginGroup (const QString & prefix )
int beginReadArray (const QString & prefix )
void beginWriteArray (const QString & prefix , int size = -1)
QStringList childGroups () const
QStringList childKeys () const
void clear ()
bool contains (const QString & key ) const
void endArray ()
void endGroup ()
bool fallbacksEnabled () const
QString fileName () const
格式 format () const
QString group () const
QTextCodec * iniCodec () const
bool isWritable () const
QString organizationName () const
void remove (const QString & key )
作用域 scope () const
void setArrayIndex (int i )
void setFallbacksEnabled (bool b )
void setIniCodec (QTextCodec * codec )
void setIniCodec (const char * codecName )
void setValue (const QString & key , const QVariant & value )
狀態 status () const
void sync ()
QVariant value (const QString & key , const QVariant & defaultValue = QVariant()) const

靜態公共成員

格式 defaultFormat ()
格式 registerFormat (const QString & extension , ReadFunc readFunc , WriteFunc writeFunc , Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive)
void setDefaultFormat (Format format )
void setPath (Format format , Scope scope , const QString & path )

重實現保護函數

virtual bool event (QEvent * event )

額外繼承成員

詳細描述

The QSettings class provides persistent platform-independent application settings.

用戶通常期望應用程序跨會話記住其設置 (窗口大小和位置、選項、等等)。此信息常存儲在 Windows 的係統注冊錶中,macOS 和 iOS 的特性列錶文件中。在缺乏標準的 Unix 係統,許多應用程序 (包括 KDE 應用程序) 使用 INI 文本文件。

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;
					

(這裏,我們還指定瞭組織的 Internet 域。當有設置時,Internet 域在 macOS 和 iOS 上被用於代替組織名稱,因為 macOS 和 iOS 應用程序按照慣例會使用 Internet 域去標識它們自己。若未設置域,則從組織名稱派生虛假域。見 特定平颱注意事項 瞭解細節)。

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 和 GUI 類型

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

區間和鍵句法

設置鍵可以包含任何 Unicode 字符。Windows 注冊錶和 INI 文件使用不區分大小寫的鍵,而在 macOS 和 iOS 上的 CFPreferences API 使用區分大小寫的鍵。為避免可移植性問題,遵循這些簡單規則:

  1. 始終使用相同大小寫,引用相同鍵。例如,若在代碼中某個地方按 text fonts 引用鍵,就不要在其它地方按 Text Fonts 引用它。
  2. 避免鍵名稱恒等,除大小寫外。例如,若擁有的鍵稱為 MainWindow ,就不要試著把另一個鍵另存為 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.

可以使用 / 字符作為分隔符來形成分層鍵,類似 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:

  1. 為 Star Runner 應用程序的特定用戶位置
  2. 由 MySoft 為所有應用程序的特定用戶位置
  3. 為 Star Runner 應用程序的係統範圍位置
  4. 由 MySoft 為所有應用程序的係統範圍位置

(見 特定平颱注意事項 瞭解在 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");
					

The 設置編輯器 範例允許您試驗不同設置位置,及啓用或禁用迴退。

還原 GUI 應用程序的狀態

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

特定平颱注意事項

存儲應用程序設置的位置

如提及在 迴退機製 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 ,默認使用下列文件:

  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. 對於每目錄 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.conf
  4. 對於每目錄 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft.conf

注意: 若 XDG_CONFIG_DIRS 未設置,默認值 /etc/xdg 被使用。

在 macOS 第 10.2 和 10.3 版,默認使用這些文件:

  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

在 Windows, NativeFormat 設置存儲在下列注冊錶路徑:

  1. HKEY_CURRENT_USER\Software\MySoft\Star Runner
  2. HKEY_CURRENT_USER\Software\MySoft\OrganizationDefaults
  3. HKEY_LOCAL_MACHINE\Software\MySoft\Star Runner
  4. HKEY_LOCAL_MACHINE\Software\MySoft\OrganizationDefaults

注意: 在 Windows,對於運行在 WOW64 模式下的 32 位程序,設置存儲在下列注冊錶路徑: HKEY_LOCAL_MACHINE\Software\WOW6432node .

若文件格式為 NativeFormat ,這是 Settings/MySoft/Star Runner.conf 在應用程序 Home (主) 目錄。

若文件格式為 IniFormat ,在 Unix、macOS 和 iOS 使用下列文件:

  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. 對於每目錄 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft/Star Runner.ini
  4. 對於每目錄 <dir> 在 $XDG_CONFIG_DIRS: <dir>/MySoft.ini

注意: 若 XDG_CONFIG_DIRS 未設置,默認值 /etc/xdg 被使用。

在 Windows,使用下列文件:

  1. FOLDERID_RoamingAppData\MySoft\Star Runner.ini
  2. FOLDERID_RoamingAppData\MySoft.ini
  3. FOLDERID_ProgramData\MySoft\Star Runner.ini
  4. 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 ()。在 Unix、macOS 和 iOS,用戶可以覆蓋它們通過設置 XDG_CONFIG_HOME 環境變量;見 setPath () 瞭解細節。

直接訪問 INI 和 .plist 文件

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.

在 macOS 和 iOS,可以訪問特性列錶 .plist 文件通過傳遞 QSettings::NativeFormat 作為第 2 自變量。例如:

QSettings settings("/Users/petra/misc/myapp.plist",
                   QSettings::NativeFormat);
					
					

直接訪問 Windows 注冊錶

在 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 公共注冊錶設置

在 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:

  • Windows 係統注冊錶有以下限製:子鍵不能超過 255 個字符,條目的值不能超過 16,383 個字符,所有鍵的值不能超過 65,535 個字符。解決這些局限性的辦法是存儲設置使用 IniFormat 而不是 NativeFormat .
  • On Windows, when the Windows system registry is used, QSettings does not preserve the original type of the value. Therefore, the type of the value might change when a new value is set. For example, a value with type REG_EXPAND_SZ 將改變為 REG_SZ .
  • 在 macOS 和 iOS, allKeys () 將為應用於所有應用程序的全局設置返迴一些額外鍵。這些鍵可以被讀取使用 value () 但無法改變,隻有陰影。調用 setFallbacksEnabled (false) 將隱藏這些全局設置。
  • On macOS and iOS, the CFPreferences API used by QSettings expects Internet domain names rather than organization names. To provide a uniform API, QSettings derives a fake domain name from the organization name (unless the organization name already is a domain name, e.g. OpenOffice.org). The algorithm appends ".com" to the company name and replaces spaces and other illegal characters with hyphens. If you want to specify a different domain name, call QCoreApplication::setOrganizationDomain (), QCoreApplication::setOrganizationName (),和 QCoreApplication::setApplicationName () 在您的 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
    
    							
  • 在 macOS,訪問不屬於當前用戶的設置的權限 (即 SystemScope ) 已於 10.7 (獅子) 版改變。在該版本之前,有 admin (管理員) 權限的用戶可以訪問這些。對於 10.7 和 10.8 (山獅) 版,隻有 root 可以。然而,10.9 (小牛隊) 版再次改變此規則,但隻針對本機格式 (plist 文件)。

另請參閱 QVariant , QSessionManager , 設置編輯器範例 ,和 應用程序範例 .

成員類型文檔編製

enum QSettings:: Format

此枚舉類型指定存儲格式,用於 QSettings .

常量 描述
QSettings::NativeFormat 0 使用最適閤平颱的存儲格式存儲設置。在 Windows,這意味著係統注冊錶;在 macOS 和 iOS,這意味著 CFPreferences API;在 Unix,這意味著以 INI 格式正文配置文件。
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 Store the settings in INI files.
QSettings::InvalidFormat 16 特殊值的返迴通過 registerFormat ().

在 Unix,NativeFormat 和 IniFormat 意味著相同事情,除文件擴展名不同外 ( .conf 為 NativeFormat, .ini 為 IniFormat)。

INI 文件格式是在所有平颱 Qt 所支持的 Windows 文件格式。在缺乏 INI 標準的情況下,我們試著遵循 Microsoft 做法,但有以下例外:

  • 若存儲類型 QVariant 無法轉換為 QString (如, QPoint , QRect ,和 QSize ),Qt 使用 @ 基句法以編碼類型。例如:
    pos = @Point(100 100)
    							

    為最小化兼容性問題,任何 @ 未齣現在值第一位置或之後未緊跟 Qt 類型 ( , Rect , Size ,等) 被視為正常字符。

  • 盡管反斜杠是 INI 文件中的特殊字符,但大多數 Windows 應用程序不轉義反斜杠 ( \ ) 在文件路徑:
    windir = C:\Windows
    							

    QSettings 始終視反斜杠為特殊字符,且不提供用於讀取或寫入這種條目的 API。

  • INI 文件格式對鍵句法有嚴格限定。Qt 要解決這是通過使用 % 作為鍵中轉義字符。此外,若保存頂層設置 (其中不帶斜綫的鍵,如 someKey),它將齣現在 INI 文件的 General 區間。為避免覆蓋其它鍵,若使用如 General/someKey 的這種鍵保存某些事情,鍵將位於 %General 區間, not 在 General 區間。
  • 遵循應該在接受的東西上是自由派,而在産生的東西上是保守派的哲學, QSettings 將接受 Latin-1 編碼 INI 文件,但生成純 ASCII 文件,使用標準 INI 轉義序列編碼其中的非 ASCII 值。要使 INI 文件更可讀 (但潛在不太兼容),調用 setIniCodec ().

另請參閱 registerFormat () 和 setPath ().

typedef QSettings:: ReadFunc

typedef 為指嚮采用以下簽名的函數指針:

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

ReadFunc 用於 registerFormat() 作為指嚮讀取一組鍵/值對的函數指針。 ReadFunc 應一次性讀取所有選項,並返迴所有設置在 SettingsMap 容器,其最初為空。

另請參閱 WriteFunc and registerFormat ().

enum QSettings:: Scope

此枚舉指定設置是具體用戶,還是由同一係統的所有用戶共享。

常量 描述
QSettings::UserScope 0 將設置存儲到當前用戶的特定位置 (如:用戶 Home 主目錄)。
QSettings::SystemScope 1 將設置存儲在全局位置,以便同一計算機中的所有用戶訪問相同設置集。

另請參閱 setPath ().

typedef QSettings:: SettingsMap

typedef 對於 QMap < QString , QVariant >.

另請參閱 registerFormat ().

enum QSettings:: Status

下列狀態值是可能的:

常量 描述
QSettings::NoError 0 沒有齣現錯誤。
QSettings::AccessError 1 發生訪問錯誤 (如:試著寫入隻讀文件)。
QSettings::FormatError 2 發生格式錯誤 (如:加載畸形 INI 文件)。

另請參閱 status ().

typedef QSettings:: WriteFunc

typedef 為指嚮采用以下簽名的函數指針:

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

WriteFunc 用於 registerFormat() 作為指嚮寫入一組鍵/值對的函數指針。 WriteFunc 僅調用一次,所以需要一次性輸齣設置。

另請參閱 ReadFunc and registerFormat ().

成員函數文檔編製

QSettings:: QSettings (const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

構造 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:: QSettings ( Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

構造 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:: QSettings ( Format format , Scope scope , const QString & organization , const QString & application = QString(), QObject * parent = Q_NULLPTR)

構造 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:: QSettings (const QString & fileName , Format format , QObject * parent = Q_NULLPTR)

構造 QSettings object for accessing the settings stored in the file called fileName ,采用父級 parent 。若文件不存在,創建它。

format is QSettings::NativeFormat ,含義對於 fileName 從屬平颱。在 Unix, fileName 是 INI 文件的名稱。在 macOS 和 iOS, fileName 是名稱對於 .plist 文件。在 Windows, fileName 是係統注冊錶路徑。

format is QSettings::IniFormat , fileName 是 INI 文件的名稱。

警告: 提供此函數是為瞭方便。它能很好地訪問 INI 或 .plist 文件生成通過 Qt,但可能失敗當在發源於其它程序的這種文件中發現某些句法時。尤其,要意識到以下局限性:

  • 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 使用 @ 字符作某些上下文元字符,以編碼 Qt 特定數據類型 (如 @Rect ),因此,可能被誤解當它齣現在純 INI 文件中時。

另請參閱 fileName ().

QSettings:: QSettings ( QObject * parent = Q_NULLPTR)

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

QStringList QSettings:: allKeys () const

返迴所有鍵的列錶 (包括子鍵),可以被讀取使用 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 ().

QString QSettings:: applicationName () const

返迴用於存儲設置的應用程序名稱。

該函數在 Qt 4.4 引入。

另請參閱 QCoreApplication::applicationName (), format (), scope (),和 organizationName ().

void QSettings:: beginGroup (const QString & prefix )

追加 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() 之前的狀態。組可以嵌套。

另請參閱 endGroup () 和 group ().

int QSettings:: beginReadArray (const QString & prefix )

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

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

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

QStringList QSettings:: childGroups () const

返迴包含可讀取鍵的所有鍵頂層組的列錶,讀取使用 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 ().

QStringList QSettings:: childKeys () const

返迴所有頂層鍵的列錶,可以被讀取使用 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 ().

void QSettings:: clear ()

移除首要位置中的所有條目,關聯此 QSettings 對象。

不移除迴退位置條目。

若隻想移除的條目在當前 group (),使用 remove("") 代替。

另請參閱 remove () 和 setFallbacksEnabled ().

bool QSettings:: contains (const QString & key ) const

返迴 true 若存在設置被稱為 key ;否則返迴 false。

若組的設置是使用 beginGroup (), key 被認為是相對於該組的。

注意:Windows 注冊錶和 INI 文件使用不區分大小寫的鍵,而 macOS 和 iOS 的 CFPreferences API 使用區分大小寫的鍵。要避免可移植性問題,見 區間和鍵句法 規則。

另請參閱 value () 和 setValue ().

[static] Format QSettings:: defaultFormat ()

返迴用於存儲設置的默認文件格式為 QSettings ( QObject *) 構造函數。若未設置默認格式, QSettings::NativeFormat 被使用。

該函數在 Qt 4.4 引入。

另請參閱 setDefaultFormat () 和 format ().

void QSettings:: endArray ()

關閉已啓動數組使用 beginReadArray () 或 beginWriteArray ().

另請參閱 beginReadArray () 和 beginWriteArray ().

void QSettings:: endGroup ()

重置組狀態先前的相應 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 ().

[virtual protected] bool QSettings:: event ( QEvent * event )

重實現自 QObject::event ().

bool QSettings:: fallbacksEnabled () const

返迴 true 若迴退被啓用;返迴 false 否則。

默認情況下,迴退是啓用的。

另請參閱 setFallbacksEnabled ().

QString QSettings:: fileName () const

返迴寫入設置的路徑,使用此 QSettings 對象存儲。

在 Windows,若格式為 QSettings::NativeFormat ,返迴值是係統注冊錶路徑,而非文件路徑。

另請參閱 isWritable () 和 format ().

Format QSettings:: format () const

返迴用於存儲設置的格式。

該函數在 Qt 4.4 引入。

另請參閱 defaultFormat (), fileName (), scope (), organizationName (),和 applicationName ().

QString QSettings:: group () const

返迴當前組。

另請參閱 beginGroup () 和 endGroup ().

QTextCodec *QSettings:: iniCodec () const

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

bool QSettings:: isWritable () const

返迴 true 若設置可以寫入使用此 QSettings 對象;返迴 false 否則。

為什麼 isWritable() 可能返迴 false 的原因之一是若 QSettings 運轉於隻讀文件。

警告: 此函數並不完美可靠,因為文件權限可以隨時改變。

另請參閱 fileName (), status (),和 sync ().

QString QSettings:: organizationName () const

返迴用於存儲設置的組織名稱。

該函數在 Qt 4.4 引入。

另請參閱 QCoreApplication::organizationName (), format (), scope (),和 applicationName ().

[static] Format QSettings:: registerFormat (const QString & extension , ReadFunc readFunc , 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 ().

void QSettings:: remove (const QString & key )

移除設置 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"]
					

注意:Windows 注冊錶和 INI 文件使用不區分大小寫的鍵,而 macOS 和 iOS 的 CFPreferences API 使用區分大小寫的鍵。要避免可移植性問題,見 區間和鍵句法 規則。

另請參閱 setValue (), value (),和 contains ().

Scope QSettings:: scope () const

返迴用於存儲設置的作用域。

該函數在 Qt 4.4 引入。

另請參閱 format (), organizationName (),和 applicationName ().

void QSettings:: setArrayIndex ( int i )

將當前數組索引設為 i 。調用函數,譬如 setValue (), value (), remove (),和 contains () 將運轉於該索引數組條目。

必須調用 beginReadArray () 或 beginWriteArray () 在可以調用此函數之前。

[static] void QSettings:: setDefaultFormat ( Format format )

將默認文件格式設為給定 format ,用於存儲設置為 QSettings ( QObject *) 構造函數。

若未設置默認格式, QSettings::NativeFormat 被使用。見文檔編製瞭解 QSettings 構造函數,查看構造函數是否會忽略此函數。

該函數在 Qt 4.4 引入。

另請參閱 defaultFormat () 和 format ().

void QSettings:: setFallbacksEnabled ( bool b )

把是否啓用迴退設為 b .

默認情況下,迴退是啓用的。

另請參閱 fallbacksEnabled ().

void QSettings:: setIniCodec ( QTextCodec * codec )

設置訪問 INI 文件的編解碼器 (包括 .conf 文件在 Unix) 到 codec 。編解碼器被用於解碼從 INI 文件讀取的任何數據,和對寫入文件的任何數據進行編碼。默認情況下,不使用編解碼器,和使用標準 INI 轉義序列編碼非 ASCII 字符。

警告: 之後必須立即設置編解碼器當創建 QSettings 對象,在訪問任何數據之前。

該函數在 Qt 4.5 引入。

另請參閱 iniCodec ().

void QSettings:: setIniCodec (const char * codecName )

這是重載函數。

設置訪問 INI 文件的編解碼器 (包括 .conf 文件在 Unix) 到 QTextCodec 為指定編碼通過 codecName 。常見值對於 codecName 包括 ISO 8859-1、UTF-8 及 UTF-16。若編碼無法識彆,則什麼都不發生。

該函數在 Qt 4.5 引入。

另請參閱 QTextCodec::codecForName ().

[static] void QSettings:: setPath ( Format format , 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 和 iOS IniFormat UserScope $HOME/.config
SystemScope /etc/xdg

默認 UserScope 路徑在 Unix、macOS 及 iOS ( $HOME/.config 或 $HOME/Settings) 可以由用戶覆蓋通過設置 XDG_CONFIG_HOME 環境變量。默認 SystemScope 路徑在 Unix、macOS 及 iOS ( /etc/xdg ) 可以被覆蓋當構建 Qt 庫使用 configure 腳本的 -sysconfdir 標誌 (見 QLibraryInfo 瞭解細節)。

設置 NativeFormat 路徑在 Windows、macOS 及 iOS,無效。

警告: 此函數不影響現有 QSettings 對象。

該函數在 Qt 4.1 引入。

另請參閱 registerFormat ().

void QSettings:: setValue (const QString & key , const QVariant & value )

設置值為設置 key to value 。若 key 已存在,先前值被覆寫。

注意:Windows 注冊錶和 INI 文件使用不區分大小寫的鍵,而 macOS 和 iOS 的 CFPreferences API 使用區分大小寫的鍵。要避免可移植性問題,見 區間和鍵句法 規則。

範例:

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

Status QSettings:: status () const

返迴狀態碼指示遇到的首個錯誤通過 QSettings ,或 QSettings::NoError 若沒有齣現錯誤。

要意識到, QSettings 延遲履行某些操作。齣於此原因,可能想要調用 sync () 以確保數據存儲在 QSettings 被寫入磁盤在調用 status() 之前。

另請參閱 sync ().

void QSettings:: sync ()

把任何未保存改變寫入永久存儲,並重新加載同時已被另一應用程序改變的任何設置。

此函數被自動調用從 QSettings 的析構函數和通過定期間隔的事件循環,因此,通常不需要自己調用它。

另請參閱 status ().

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

返迴值為設置 key 。若設置不存在,返迴 defaultValue .

若未指定默認值,默認 QVariant 被返迴。

注意:Windows 注冊錶和 INI 文件使用不區分大小寫的鍵,而 macOS 和 iOS 的 CFPreferences API 使用區分大小寫的鍵。要避免可移植性問題,見 區間和鍵句法 規則。

範例:

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
					

另請參閱 setValue (), contains (),和 remove ().