[导读]​(本文为utf-8格式,可以直接使用相应代码)   Models 是用来提供数据的,它既可以以 QML 的形式出现也可以是 C++的类。QML中的Model有ListModel、XmlListMode

(本文为utf-8格式,可以直接使用相应代码)   

Models 是用来提供数据的,它既可以以 QML 的形式出现也可以是 C++的类。QML中的Model有ListModel、XmlListModel、VisualItemModel;C++ 中的 Model 有 QAbstractItemModel、QStringList、 QList等。另外我们可以把数据存到数据库里,程序启动的时候从数据库中读取数据,退出的时候把Model中的数据存放回数据库中。主要代码如下所示:

ListModel {
id: mymodel
Component.onCompleted: loadImageData()
Component.onDestruction: saveImageData()
function loadImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
// Create the database if it doesn't already exist
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');

var rs = tx.executeSql('SELECT * FROM Images');
var index = 0;
if (rs.rows.length > 0) {
var index = 0;
while (index < rs.rows.length) {
var myItem = rs.rows.item(index);
mymodel.append( {
"id": myItem.id,
"title": myItem.title ,
"picture": myItem.picture });
index++;
}
} else {
mymodel.append( {
"id": 1,
"title": 'apple' ,
"picture": 'content/pics/apple.png' });
mymodel.append( {
"id": 2,
"title": 'Qt Quick!' ,
"picture": 'content/pics/Qt.png' });
}
}
)
}

function saveImageData() {
var db = openDatabaseSync("MyDB", "1.0", "My model SQL", 50000);
db.transaction(
function(tx) {
tx.executeSql('DROP TABLE Images');
tx.executeSql('CREATE TABLE IF NOT EXISTS Images(id INTEGER primary key, title TEXT, picture TEXT)');
var index = 0;
while (index < mymodel.count) {
var myItem = mymodel.get(index);
tx.executeSql('INSERT INTO Images VALUES(?,?,?)', [myItem.id, myItem.title, myItem.picture]);
index++;
}
}
)
}
}

动态添加数据是非常简单的,比如我们在 onClicked 事件中可以这样做:


onClicked:  mymodel.append( { "title": 'Qt', "picture": 'content/pics/Qt.png'  })


删除数据:

onClicked: mymodel.remove(listView.currentIndex)

下面是官方文档:

Offline Storage APIDatabase API

The openDatabaseSync() and related functions provide the ability to access local offline storage in an SQL database.

These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the Databases subdirectory of QDeclarativeEngine::offlineStoragePath(), currently as SQLite databases.

The API can be used from JavaScript functions in your QML:

import Qt 4.7

Text {
text: "?"

function findGreetings() {
var db = openDatabaseSync("QDeclarativeExampleDB", "1.0", "The Example QML SQL!", 1000000);

db.transaction(
function(tx) {
// Create the database if it doesn't already exist
tx.executeSql('CREATE TABLE IF NOT EXISTS Greeting(salutation TEXT, salutee TEXT)');

// Add (another) greeting row
tx.executeSql('INSERT INTO Greeting VALUES(?, ?)', [ 'hello', 'world' ]);

// Show all added greetings
var rs = tx.executeSql('SELECT * FROM Greeting');

var r = ""
for(var i = 0; i < rs.rows.length; i++) {
r += rs.rows.item(i).salutation + ", " + rs.rows.item(i).salutee + "n"
}
text = r
}
)
}

Component.onCompleted: findGreetings()
}