在QML中,可以使用`TableView`和`TableViewColumn`类型来创建表格,并使用模型来提供数据。这里给出一个官方示例,展示如何在QML中使用表格:
```qml
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Table View Example"
// 定义模型
ListModel {
id: myModel
ListElement {
name: "John"
age: 28
country: "USA"
}
ListElement {
name: "Jane"
age: 32
country: "Canada"
}
ListElement {
name: "Tom"
age: 45
country: "UK"
}
}
// 创建表格视图
TableView {
id: tableView
model: myModel
anchors.fill: parent
clip: true
focus: true
selectionMode: TableView.SingleSelection
alternatingRowColors: true
highlightRangeMode: TableView.ApplyRange
highlightFollowsCurrentItem: true
cacheBuffer: 10000000 // Enable caching to improve performance.
// 创建表格列
TableViewColumn {
role: "name"
title: "Name"
width: 200
}
TableViewColumn {
role: "age"
title: "Age"
width: 100
}
TableViewColumn {
role: "country"
title: "Country"
width: 150
}
}
}
```
在这个示例中,首先定义了一个`ListModel`,它包含了三个`ListElement`,每个元素都有`name`、`age`和`country`属性。然后,创建了一个`TableView`,并将模型设置为`myModel`。表格视图中的每一行都与模型中的一个元素相对应。然后,定义了三个表格列,通过设置`role`属性来指定与每个列对应的模型属性。