Save your Qt Quick app settings easily with LocalStorage

Every application need to store smaller and larger information persistently. This can be done locally on the file system or remote on a server.

Qt comes with an LocalStorage API, which provides the ability to access local offline storage in an SQL database from QML and JavaScript. The underlying file is an sqlite database. It can be opened up with an sqlite manager and can be edited, also you can execute sql specific commands like select, insert and so on.  For detailed description LocalStorage Documentation.

We use this API to save app settings in a quicker way. First of all let us begin with a example hello world application:

import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    visible: true
    width: 400
    height: 400

 MouseArea {
     anchors.fill: parent
     onClicked: {
         textlabel.text = textinput.text
     }
 }

 TextField {
     id: textinput
     placeholderText: "text"
     anchors.centerIn: parent
 }

 Text {
     id: textlabel
     anchors.horizontalCenter: parent.horizontalCenter
     anchors.top: textinput.bottom
 }

}

If you click on the mouse area, then the text in the TextField component will setted to the Text component. Our goal is to save this entered text as app setting. If the application restarts load the setting and set it to the Text component.  For this we can use LocalStorage and a small snippet of code:

.import QtQuick.LocalStorage 2.0 as Storage

function getDatabase() {
    return Storage.LocalStorage.openDatabaseSync("HelloApp",          "0.1", "HelloAppDatabase", 100);
}


function set(setting, value) {
    var db = getDatabase();
    var res = "";
    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS                     settings(setting TEXT UNIQUE, value TEXT)');
        var rs = tx.executeSql('INSERT OR REPLACE INTO                settings VALUES (?,?);', [setting,value]);
             if (rs.rowsAffected > 0) {
                res = "OK";
             } else {
                res = "Error";
             }
       }
    );
    return res;
}

function get(setting, default_value) {
    var db = getDatabase();
    var res="";
    try {
       db.transaction(function(tx) {
          var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]);
             if (rs.rows.length > 0) {
                res = rs.rows.item(0).value;
             } else {
                res = default_value;
             }
       })
    } catch (err) {
        console.log("Database " + err);
       res = default_value;
    };
    return res
}

In your project create a JavaScript file paste this code and save it as storage.js

And now we use this in main.qml to set and get app settings.

import QtQuick 2.3
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import "storage.js" as Storage

Window {
    visible: true
    width: 400
    height: 400

Component.onCompleted: {
    textlabel.text = Storage.get("labeltext", "Hello World") //storage get
}

MouseArea {
    anchors.fill: parent
    onClicked: {
        textlabel.text = textinput.text
        Storage.set("labeltext", textlabel.text) //storage
    }
}

TextField {
    id: textinput
    placeholderText: "text"
    anchors.centerIn: parent
}

Text {
    id: textlabel
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.top: textinput.bottom
}

}
storage.js is imported as Storage. The syntax for saving is

Storage.set([identifier], value)

In our example we used:

Storage.set("labeltext", textlabel.text)

 

Syntax for loading:

Storage.set([identifier], defaultvalue)

We load the settings at the start and set the value to the component with:

textlabel.text = Storage.get("labeltext", "Hello World")

Here will the Storage.get method search for the identifier in the database. If the id is not existining, it uses the default value, which is given here as „Hello World“. If the id exists, then the method grab the value, which we saved before with the Storage.set method and set the value to text component.

storage.js can be used overall in your project for saving and loading settings.

 

The path for the databases are varying between different operating systems.

on Linux :

/home/fecub/.local/share/applicationname/QML/OfflineStorage/Databases

on Windows:

C:\Users\fecub\AppData\Local\applicationname\QML\OfflineStorage\Databases\

on Mac:

/Users/fecub/Library/Application\ Support/applicationname/QML/OfflineStorage/Databases

the file is saved as [hashnumber].sqlite

For the complete project, please visit: github.com/fecub

source: askubuntuqt.io / Data StorageLocalStorage Documentation

4 Antworten zu “Save your Qt Quick app settings easily with LocalStorage

  1. how to save an array?

    Storage.set(„how save an array?“, array)

    if array is an array, this solution doesn’t work. Any suggestions? many thanks

    • i think it’s impossible to save directly an array type.
      But what you can do is to loop the array and save the value each loop.

      for example:
      “‘
      var exampleArray = [„Hello“,“Qt“,“storage“];
      var arrayLength = exampleArray.length;
      for (var i = 0; i < arrayLength; i++) {
      Storage.set ("array"+i, exampleArray [i])
      }
      // CODE IS NOT TESTED
      '''

      • I found another solution (code tested):
        Storage.set(„myArray“, JSON.stringify(myArray));
        myArray = JSON.parse(Storage.get(„myArray“));

        Bye🙂

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s