In the program, we often need to persist some data, such as some setting information and program configuration. QML does not directly access local files, but it can be accessed through
The Offline Storage API accesses the local Sqlite database to achieve its purpose.
First create a storage.js in the qml directory
- //storage.js
- // First create a helper method to connect to the database
.import QtQuick.LocalStorage 2.0 as Sql
- function getDatabase() {
- return Sql.LocalStorage.openDatabaseSync("MyAppName", "1.0", "StorageDatabase", 100000);
- }
- // When the program is opened, initialize the table
- function initialize() {
- var db = getDatabase();
- db.transaction(
- function(tx) {
- // If the setting table does not exist, create one
- // If the table exists, skip this step
- tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');
- });
- }
- // insert data
- function setSetting(setting, value) {
- var db = getDatabase();
- var res = "";
- db.transaction(function(tx) {
- var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);
- //console.log(rs.rowsAffected)
- if (rs.rowsAffected > 0) {
- res = "OK";
- } else {
- res = "Error";
- }
- }
- );
- return res;
- }
- // 获取数据
- function getSetting(setting) {
- var db = getDatabase();
- var res="";
- 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 = "Unknown";
- }
- })
- return res
- }
然后就可以在qml里调用了
- import Qt 4.7
- //引入storage.js,起个别名Storage,以供后面使用
- import "storage.js"as Storage
- Rectangle {
- width: 360
- height: 360
- id: screen
- Text {
- id: textDisplay
- anchors.centerIn: parent
- }
- Component.onCompleted: {
- // initialize the database
- Storage.initialize();
- // assign
- Storage.setSetting("mySetting","myValue");
- //Get a value and write it in textDisplay
- textDisplay.text = "The value of mySetting is:\n" + Storage.getSetting("mySetting");
- }
- }