Qml listview sqlite coding
时间: 2023-07-24 14:32:08 浏览: 47
以下是在 QML 中使用 SQLite 数据库和 ListView 组件的代码示例:
```qml
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import QtQuick.Dialogs 1.0
import QtQuick.LocalStorage 2.0
import QtSql 2.0
ApplicationWindow {
id: mainWindow
visible: true
width: 400
height: 400
title: "SQLite ListView"
// Open the SQLite database
Component.onCompleted: {
var db = QtSql.openDatabaseSync("mydatabase", "1.0", "My database", 1000000);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS items(name TEXT, description TEXT)');
tx.executeSql('INSERT INTO items VALUES("Item 1", "Description 1")');
tx.executeSql('INSERT INTO items VALUES("Item 2", "Description 2")');
tx.executeSql('INSERT INTO items VALUES("Item 3", "Description 3")');
tx.executeSql('INSERT INTO items VALUES("Item 4", "Description 4")');
});
}
// Define the ListView
ListView {
id: listView
anchors.fill: parent
model: ListModel {
id: listModel
Component.onCompleted: {
var db = QtSql.openDatabaseSync("mydatabase", "1.0", "My database", 1000000);
var res = db.transaction(function(tx) {
return tx.executeSql('SELECT * FROM items');
});
for (var i = 0; i < res.rows.length; i++) {
var row = res.rows.item(i);
listModel.append({
"name": row.name,
"description": row.description
});
}
}
}
// Define the delegate for the ListView
delegate: Rectangle {
width: parent.width
height: 50
color: index % 2 == 0 ? "#f0f0f0" : "#ffffff"
Text {
text: name
font.bold: true
font.pixelSize: 18
anchors.verticalCenter: parent.verticalCenter
anchors.leftMargin: 10
}
Text {
text: description
font.pixelSize: 14
color: "darkgray"
anchors.verticalCenter: parent.verticalCenter
anchors.rightMargin: 10
anchors.right: parent.right
}
}
}
}
```
在上面的示例中,我们首先使用 QtSql 包中的 openDatabaseSync 函数打开 SQLite 数据库,并在其中创建一个名为 items 的表,并插入一些数据。然后,我们使用 ListModel 组件来从 SQLite 数据库中读取数据,并将其绑定到 ListView 组件的 model 属性上。最后,我们定义了一个委托来显示每个列表项的名称和描述。