Use QML Localstorage to store our data

Source: Internet
Author: User
Tags sqlite database

In the previous example, we could "use the SQLite offline storage API to store the app's settings". We also show how to store the JSON we need in a local file in the example "How to dynamically modify the data in the Listmodel in the QML application and store it in JSON format". In this article, we will use the localstorage provided by Qtquick to store the data we need.


To illustrate the problem, I'll start by creating a template based on the "QtQuick App with QML UI (qmake)". First we revise our main.cpp as follows:


Main.qml
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include < Qdebug>int Main (int argc, char *argv[]) {    qguiapplication app (argc, argv);    Qquickview view;    Qdebug () << "Local Storage path:" << view.engine ()->offlinestoragepath ();    Qobject::connect (View.engine (), SIGNAL (Quit ()), Qapp, SLOT (Quit ()));    View.setsource (Qurl (qstringliteral ("qrc:///main.qml"));    View.setresizemode (Qquickview::sizerootobjecttoview);    View.show ();    return app.exec ();}

When we run our application, we can see:
Local Storage path:  "/home/phablet/.local/share/localstorage/qml/offlinestorage"

This path is obviously different from the actual path we produce when we actually run it on the phone:


This also shows that the implementation on Ubuntu is different from the standard QT implementation. From the above we can see that the time path of the database is:
[Email protected]:~/.local/share/localstorage.liu-xiao-guo/databases$ Ls4ff10001f402923590ceb1d12a0cffc6.ini  4ff10001f402923590ceb1d12a0cffc6.sqlite


To enable the application to exit itself, we have added the following statement:
  Qobject::connect (View.engine (), SIGNAL (Quit ()), Qapp, SLOT (Quit ()));

This allows the app to exit when you use Qt.quit () in our QML code. This is different from our general design. We generally do not need to do this. For this application, we would like to get an event at the exit to save our settings, all of which we have such a special treatment.

In order to be able to access the SQLite database, we designed the following Database.js file:
Database.js
. Import Qtquick.localstorage 2.0 as Sqlvar db;function initdatabase () {print (' initdatabase () ') db = Sql.localstorag    E.opendatabasesync ("Crazybox", "1.0", "A box who remembers its position", 100000);  Db.transaction (Function (TX) {print (' ... create table ') tx.executesql (' CREATE table IF not ' EXISTS data (name    text, value text) '); });}    function ReadData () {print (' readdata () ') if (!db) {return;}  Db.transaction (Function (TX) {print (' ... read crazy object ') var result = Tx.executesql (' select * ' from data        where name= "crazy");            if (result.rows.length = = = 1) {print (' ... update crazy geometry ')/Get the Value column            var value = Result.rows[0].value;            Convert to JS object var obj = json.parse (value)//apply to Object crazy.x = obj.x;        CRAZY.Y = OBJ.Y; }    });}    function StoreData () {print (' storedata () ') if (!db) {return;} Db.transactiOn (function (TX) {print (' ... check if a crazy object exists ') var result = Tx.executesql (' SELECT * from dat        A WHERE name = "Crazy");        Prepare object to be stored as JSON var obj = {x:crazy.x, y:crazy.y}; if (result.rows.length = = = 1) {//Use update print (' ... crazy exists, update it ') result = Tx.execute        SQL (' UPDATE data set value=? Where Name= ' crazy "', [Json.stringify (obj)]); } else {//Use Insert print (' ... crazy does not exists, create it ') result = Tx.executesql (' Insert        into Data VALUES (?,?) ', [' Crazy ', json.stringify (obj)]); }    });}

Here, we can create a database called "Crazybox" and produce a table in it called data. We can update the data to the table. From this example, we can see that this method is used to store our JSON data without using the C + + code (the reference routine "how to dynamically modify the data in the Listmodel in the QML application and store it in JSON format"). This is good news for most developers who are not very familiar with C + + code.

Main.qml
Import QtQuick 2.0import ubuntu.components 1.1import "Database.js" as db/*! \brief MainView with a Label and Button Elements.*/mainview {//ObjectName for functional testing purposes (autopilot- QT5) ObjectName: "MainView"//note! ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Localstorage.liu-xiao-guo"/ * The enables the application to change orientation when the device is rotated.    The default is False.    *///automaticorientation:true//Removes the old toolbar and enables new features of the new header.         Usedeprecatedtoolbar:false width:units.gu (height:units.gu) page {title:i18n.tr ("Localstorage")            Rectangle {id:crazy objectName: ' Crazy ' width:200 height:200                 x:50 y:50 color: "#53d769" border.color:Qt.lighter (color, 1.1) Text { Anchors.centerin: Parent Text:Math.round (parent.x) + '/' + Math.Round (PARENT.Y)} mousearea {            Anchors.fill:parent Drag.target:parent}} component.oncompleted: {            Db.initdatabase ();            Print ("It is going to read data");        Db.readdata ();            } component.ondestruction: {print ("It is going to save data");        Db.storedata (); } Button {Anchors.bottom:parent.bottom anchors.bottomMargin:units.gu (1) anchors            . HorizontalCenter:parent.horizontalCenter text: "Close" onclicked: {qt.quit (); }        }    }}


Our MAIN.QML design is very simple. After the UI is loaded, we initialize the database and read the data that has been stored. If the data already exists, read it out and initialize our rectangle "crazy". When the app exits, we store our data. It should be noted that when we use our fingers to drag and drop the app, our app does not accept the following events:
        Component.ondestruction: {            print ("It is going to save data");            Db.storedata ();        }

We have to get this event by selecting the "Quit" button.
To run our application:



Whenever we exit the app and restart the app, we can see that our green squares are in the same position as the last time we exited.
The source code for the entire project is: Git clone https://gitcafe.com/ubuntu/localstorage.git

Use QML Localstorage to store our data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.