Settings
设置
Qt comes with a Settings
element for loading and storing settings. The is still in the lab’s module, which means the API may break in the future. So be aware.
Qt带有一个用于加载和存储设置的设置元素类型Settings
。该API仍在实验室的模块中,这意味着该API将来可能会大变。所以要注意。
Here is a small example which applies a color value to a base rectangle. Every time the user clicks on the window a new random color is generated. When the application is closed and relaunched again you should see your last color. The default color should be the color initially set on the root rectangle.
下面是一个将颜色值应用于基础矩形的小示例。每次用户点击窗口,就会产生一种新的随机颜色。当应用程序关闭并再次启动时,您应该会看到最后一种颜色。默认颜色应该是最初在根矩形上设置的颜色。
import QtQuick
import Qt.labs.settings 1.0
Rectangle {
id: root
width: 320
height: 240
color: '#fff' // default color
Settings {
property alias color: root.color
}
MouseArea {
anchors.fill: parent
// random color
onClicked: root.color = Qt.hsla(Math.random(), 0.5, 0.5, 1.0);
}
}
The settings value are stored every time the value changes. This might be not always what you want. To store the settings only when required you can use standard properties combined with a function that alters the setting when called.
每次值更改时,都会存储设置值。这可能并不总是你想要的。要仅在需要时存储设置,可以将标准属性与调用时更改设置的函数结合使用。
Rectangle {
id: root
color: settings.color
Settings {
id: settings
property color color: '#000000'
}
function storeSettings() { // executed maybe on destruction
settings.color = root.color
}
}
It is also possible to group settings into different categories using the category
property.
还可以使用“category
”属性将设置分组到不同的类别中。
Settings {
category: 'window'
property alias x: window.x
property alias y: window.x
property alias width: window.width
property alias height: window.height
}
The settings are stored according to your application name, organization, and domain. This information is normally set in the main function of your C++ code.
这些设置是根据应用程序名称、组织和域存储的。此信息通常设置在C++代码的主要功能中。
int main(int argc, char** argv) {
...
QCoreApplication::setApplicationName("Awesome Application");
QCoreApplication::setOrganizationName("Awesome Company");
QCoreApplication::setOrganizationDomain("org.awesome");
...
}
If you are writing a pure QML application, you can set the same attributed using the global properties Qt.application.name
, Qt.application.organization
, and Qt.application.domain
.
如果您正在编写纯QML应用程序,则可以使用相同全局属性Qt.application.name
, Qt.application.organization
和Qt.application.domain