TableView详细例程
时间: 2023-09-14 14:07:25 浏览: 49
下面是一个更详细的TableView示例,展示了如何在QML中使用TableView并对其进行更多的自定义和交互:
```qml
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 600
height: 400
TableView {
anchors.fill: parent
TableViewColumn {
role: "name"
title: "Name"
width: 200
}
TableViewColumn {
role: "age"
title: "Age"
width: 100
}
TableViewColumn {
role: "city"
title: "City"
width: 200
}
model: ListModel {
ListElement { name: "John"; age: 30; city: "New York" }
ListElement { name: "Alice"; age: 25; city: "London" }
ListElement { name: "Bob"; age: 35; city: "Paris" }
}
delegate: Item {
width: parent.width
height: 50
Rectangle {
color: styleData.row % 2 === 0 ? "#F0F0F0" : "#FFFFFF"
border.color: "black"
border.width: 1
anchors.fill: parent
Text {
text: styleData.value
anchors.centerIn: parent
}
}
MouseArea {
anchors.fill: parent
onClicked: {
console.log("Clicked on row:", styleData.row)
}
}
}
onCurrentRowChanged: {
console.log("Current row changed:", currentRow)
}
}
}
```
这个例子创建了一个包含3列的TableView,用于显示姓名、年龄和城市。每个列都有一个role属性来指定数据的角色,以及一个title属性来定义列的标题,还有一个width属性来设置列的宽度。
在model属性中,我们使用ListModel作为表格的数据模型,并在模型中添加了三个数据项。每个数据项都包含一个name、age和city属性。
在delegate属性中,我们使用Item作为每个单元格的代理,并定义了单元格的外观和交互。外观部分使用一个矩形和一个文本元素来显示单元格的值,并根据行数的奇偶性设置不同的背景颜色。交互部分使用MouseArea来捕获单元格的点击事件,并在控制台打印出点击的行号。
在onCurrentRowChanged信号处理程序中,我们监听当前行的变化,并在控制台打印出当前行的行号。
你可以根据需要进一步自定义TableView的样式和交互行为。这个示例为你提供了一个基础的起点来构建自己的TableView应用程序。