?? qsettings.cpp
字號:
QString currentSection; int currentSectionStart = 0; int dataPos = 0; int lineStart; int lineLen; int equalsPos; bool ok = true; while (readIniLine(data, dataPos, lineStart, lineLen, equalsPos)) { char ch = data.at(lineStart); if (ch == '[') { FLUSH_CURRENT_SECTION(); // this is a section QByteArray iniSection; int idx = data.indexOf(']', lineStart); if (idx == -1 || idx >= lineStart + lineLen) { ok = false; iniSection = data.mid(lineStart + 1, lineLen - 1); } else { iniSection = data.mid(lineStart + 1, idx - lineStart - 1); } iniSection = iniSection.trimmed(); if (qstricmp(iniSection, "general") == 0) { currentSection.clear(); } else { if (qstricmp(iniSection, "%general") == 0) { currentSection = QLatin1String(iniSection.constData() + 1); } else { currentSection.clear(); iniUnescapedKey(iniSection, 0, iniSection.size(), currentSection); } currentSection += QLatin1Char('/'); } currentSectionStart = dataPos; } } Q_ASSERT(lineStart == data.length()); FLUSH_CURRENT_SECTION(); return ok;#undef FLUSH_CURRENT_SECTION}bool QConfFileSettingsPrivate::readIniSection(const QSettingsKey §ion, const QByteArray &data, ParsedSettingsMap *settingsMap){ QStringList strListValue; bool sectionIsLowercase = (section == section.originalCaseKey()); int equalsPos; bool ok = true; int dataPos = 0; int lineStart; int lineLen; while (readIniLine(data, dataPos, lineStart, lineLen, equalsPos)) { char ch = data.at(lineStart); Q_ASSERT(ch != '['); if (equalsPos == -1) { if (ch != ';') ok = false; continue; } int keyEnd = equalsPos; while (keyEnd > lineStart && ((ch = data.at(keyEnd - 1)) == ' ' || ch == '\t')) --keyEnd; int valueStart = equalsPos + 1; QString key = section.originalCaseKey(); bool keyIsLowercase = (iniUnescapedKey(data, lineStart, keyEnd, key) && sectionIsLowercase); QString strValue; strValue.reserve(lineLen - (valueStart - lineStart)); bool isStringList = iniUnescapedStringList(data, valueStart, lineStart + lineLen, strValue, strListValue); QVariant variant; if (isStringList) { variant = stringListToVariantList(strListValue); } else { variant = stringToVariant(strValue); } /* We try to avoid the expensive toLower() call in QSettingsKey by passing Qt::CaseSensitive when the key is already in lowercase. */ settingsMap->insert(QSettingsKey(key, keyIsLowercase ? Qt::CaseSensitive : IniCaseSensitivity), variant); } return ok;}bool QConfFileSettingsPrivate::writeIniFile(QIODevice &device, const ParsedSettingsMap &map){ typedef QMap<QString, QVariantMap> IniMap; IniMap iniMap; IniMap::const_iterator i;#ifdef Q_OS_WIN const char * const eol = "\r\n";#else const char eol = '\n';#endif for (ParsedSettingsMap::const_iterator j = map.constBegin(); j != map.constEnd(); ++j) { QString section; QString key = j.key().originalCaseKey(); int slashPos; if ((slashPos = key.indexOf(QLatin1Char('/'))) != -1) { section = key.left(slashPos); key.remove(0, slashPos + 1); } iniMap[section][key] = j.value(); } bool writeError = false; for (i = iniMap.constBegin(); !writeError && i != iniMap.constEnd(); ++i) { QByteArray realSection; iniEscapedKey(i.key(), realSection); if (realSection.isEmpty()) { realSection = "[General]"; } else if (qstricmp(realSection, "general") == 0) { realSection = "[%General]"; } else { realSection.prepend('['); realSection.append(']'); } if (i != iniMap.constBegin()) realSection.prepend(eol); realSection += eol; device.write(realSection); const QVariantMap &ents = i.value(); for (QVariantMap::const_iterator j = ents.constBegin(); j != ents.constEnd(); ++j) { QByteArray block; iniEscapedKey(j.key(), block); block += '='; const QVariant &value = j.value(); /* The size() != 1 trick is necessary because QVariant(QString("foo")).toList() returns an empty list, not a list containing "foo". */ if (value.type() == QVariant::StringList || (value.type() == QVariant::List && value.toList().size() != 1)) { iniEscapedStringList(variantListToStringList(value.toList()), block); } else { iniEscapedString(variantToString(value), block); } block += eol; if (device.write(block) == -1) { writeError = true; break; } } } return !writeError;}void QConfFileSettingsPrivate::ensureAllSectionsParsed(QConfFile *confFile) const{ UnparsedSettingsMap::const_iterator i = confFile->unparsedIniSections.constBegin(); const UnparsedSettingsMap::const_iterator end = confFile->unparsedIniSections.constEnd(); for (; i != end; ++i) { if (!QConfFileSettingsPrivate::readIniSection(i.key(), i.value(), &confFile->originalKeys)) setStatus(QSettings::FormatError); } confFile->unparsedIniSections.clear();}void QConfFileSettingsPrivate::ensureSectionParsed(QConfFile *confFile, const QSettingsKey &key) const{ if (confFile->unparsedIniSections.isEmpty()) return; UnparsedSettingsMap::iterator i; int indexOfSlash = key.indexOf(QLatin1Char('/')); if (indexOfSlash != -1) { i = confFile->unparsedIniSections.upperBound(key); if (i == confFile->unparsedIniSections.begin()) return; --i; if (i.key().isEmpty() || !key.startsWith(i.key())) return; } else { i = confFile->unparsedIniSections.begin(); if (i == confFile->unparsedIniSections.end() || !i.key().isEmpty()) return; } if (!QConfFileSettingsPrivate::readIniSection(i.key(), i.value(), &confFile->originalKeys)) setStatus(QSettings::FormatError); confFile->unparsedIniSections.erase(i);}/*! \class QSettings \brief The QSettings class provides persistent platform-independent application settings. \ingroup io \ingroup misc \mainclass \reentrant Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files. QSettings is an abstraction around these technologies, enabling you to save and restore application settings in a portable manner. It also supports \l{registerFormat()}{custom storage formats}. QSettings's API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort. If all you need is a non-persistent memory-based structure, consider using QMap<QString, QVariant> instead. \tableofcontents section1 \section1 Basic Usage When creating a QSettings object, you must pass the name of your company or organization as well as the name of your application. For example, if your product is called Star Runner and your company is called MySoft, you would construct the QSettings object as follows: \quotefromfile snippets/settings/settings.cpp \skipuntil snippet_ctor1 \skipline { \printline QSettings settings QSettings objects can be created either on the stack or on the heap (i.e. using \c new). Constructing and destroying a QSettings object is very fast. If you use QSettings from many places in your application, you might want to specify the organization name and the application name using QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName(), and then use the default QSettings constructor: \skipuntil snippet_ctor2 \skipline { \printline setOrganizationName \printline setOrganizationDomain \printline setApplicationName \dots \printline QSettings settings; (Here, we also specify the organization's Internet domain. When the Internet domain is set, it is used on Mac OS X instead of the organization name, since Mac OS X applications conventionally use Internet domains to identify themselves. If no domain is set, a fake domain is derived from the organization name. See the \l{Platform-Specific Notes} below for details.) QSettings stores settings. Each setting consists of a QString that specifies the setting's name (the \e key) and a QVariant that stores the data associated with the key. To write a setting, use setValue(). For example: \printline setValue( If there already exists a setting with the same key, the existing value is overwritten by the new value. For efficiency, the changes may not be saved to permanent storage immediately. (You can always call sync() to commit your changes.) You can get a setting's value back using value(): \printline settings.value( If there is no setting with the specified name, QSettings returns a null QVariant (which can be converted to the integer 0). You can specify another default value by passing a second argument to value(): \skipline { \printline /settings.value\(.*,.*\)/ \skipline } To test whether a given key exists, call contains(). To remove the setting associated with a key, call remove(). To obtain the list of all keys, call allKeys(). To remove all keys, call clear(). \section1 QVariant and GUI Types Because QVariant is part of the \l QtCore library, it cannot provide conversion functions to data types such as QColor, QImage, and QPixmap, which are part of \l QtGui. In other words, there is no \c toColor(), \c toImage(), or \c toPixmap() functions in QVariant. Instead, you can use the QVariant::value() or the qVariantValue() template function. For example: \code QSettings settings("MySoft", "Star Runner"); QColor color = settings.value("DataPump/bgcolor").value<QColor>(); \endcode The inverse conversion (e.g., from QColor to QVariant) is automatic for all data types supported by QVariant, including GUI-related types: \code QSettings settings("MySoft", "Star Runner"); QColor color = palette().background().color(); settings.setValue("DataPump/bgcolor", color); \endcode Custom types registered using qRegisterMetaType() and qRegisterMetaTypeStreamOperators() can be stored using QSettings. \section1 Key Syntax Setting keys can contain any Unicode characters. The Windows registry and INI files use case-insensitive keys, whereas the Carbon Preferences API on Mac OS X uses case-sensitive keys. To avoid portability problems, follow these two simple rules: \list 1 \o Always refer to the same key using the same case. For example, if you refer to a key as "text fonts" in one place in your code, don't refer to it as "Text Fonts" somewhere else. \o Avoid key names that are identical except for the case. For example, if you have a key called "MainWindow", don't try to save another key as "mainwindow". \endlist You can form hierarchical keys using the '/' character as a separator, similar to Unix file paths. For example: \printline setValue \printline setValue \printline setValue If you want to save or restore many settings with the same prefix, you can specify the prefix using beginGroup() and call endGroup() at the end. Here's the same example again, but this time using the group mechanism: \printline beginGroup \printuntil endGroup \printline beginGroup \printuntil endGroup If a group is set using beginGroup(), the behavior of most functions changes consequently. Groups can be set recursively. In addition to groups, QSettings also supports an "array" concept. See beginReadArray() and beginWriteArray() for details. \section1 Fallback Mechanism Let's assume that you have created a QSettings object with the organization name MySoft and the application name Star Runner. When you look up a value, up to four locations are searched in that order: \list 1 \o a user-specific location for the Star Runner application \o a user-specific location for all applications by MySoft \o a system-wide location for the Star Runner application \o a system-wide location for all applications by MySoft \endlist (See \l{Platform-Specific Notes} below for information on what these locations are on the different platforms supported by Qt.) If a key cannot be found in the first location, the search goes on in the second location, and so on. This enables you to store system-wide or organization-wide settings and to override them on a per-user or per-application basis. To turn off this mechanism, call setFallbacksEnabled(false). Although keys from all four locations are available for reading, only the first file (the user-specific location for the application at hand) is accessible for writing. To write to any of the other files, omit the application name and/or specify QSettings::SystemScope (as opposed to QSettings::UserScope, the default). Let's see with an example: \skipuntil snippet_locations \skipline {
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -