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.

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.

  1. import QtQuick
  2. import Qt.labs.settings 1.0
  3. Rectangle {
  4. id: root
  5. width: 320
  6. height: 240
  7. color: '#fff' // default color
  8. Settings {
  9. property alias color: root.color
  10. }
  11. MouseArea {
  12. anchors.fill: parent
  13. // random color
  14. onClicked: root.color = Qt.hsla(Math.random(), 0.5, 0.5, 1.0);
  15. }
  16. }

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.

  1. Rectangle {
  2. id: root
  3. color: settings.color
  4. Settings {
  5. id: settings
  6. property color color: '#000000'
  7. }
  8. function storeSettings() { // executed maybe on destruction
  9. settings.color = root.color
  10. }
  11. }

It is also possible to group settings into different categories using the category property.

  1. Settings {
  2. category: 'window'
  3. property alias x: window.x
  4. property alias y: window.x
  5. property alias width: window.width
  6. property alias height: window.height
  7. }

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.

  1. int main(int argc, char** argv) {
  2. ...
  3. QCoreApplication::setApplicationName("Awesome Application");
  4. QCoreApplication::setOrganizationName("Awesome Company");
  5. QCoreApplication::setOrganizationDomain("org.awesome");
  6. ...
  7. }

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.