QML < 7 > 基于ListView 实现表格显示
前言
本文记录一种基于ListView 实现表格显示的一种方式,在QML中也可直接选择TableView进行表格显示,示例程序QML <4> Tableview 自定义表格显示
一、实现方式
以行的方式去处理,每行用RowLayout布局列Component,表头和表格内容分开,并用ColumnLayout布局
二、示例
1.表头
表头数据定义:
property var header_data:
[
{"column_name":"column_role_1","width_ratio":0.2,"column_color":"red"},
{"column_name":"column_role_2","width_ratio":0.3,"column_color":"gray"},
{"column_name":"column_role_3","width_ratio":0.4,"column_color":"darkgray"}
]
表头实现:
Rectangle
{
id:table_header
Layout.fillWidth: true
Layout.preferredHeight: 60
RowLayout
{
anchors.fill: parent
spacing: 0
Repeater
{
model: header_data
Rectangle
{
Layout.preferredWidth: modelData.width_ratio * parent.width
Layout.fillHeight: true
color: modelData.column_color
// 列名
Text {
anchors.fill: parent
color: "#FFFFFF"
font.family: "Microsoft YaHei"
font.pixelSize: 18
font.weight: Font.Normal
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
wrapMode: Text.WordWrap
text: modelData.column_name
}
}
}
Item {
Layout.fillWidth: true
Layout.fillHeight: true
}
}
列显示比例:
Layout.preferredWidth: modelData.width_ratio * parent.width
类似弹簧(QSpacerItem)填补空白:
Item 类型是 Qt Quick 中所有可视项的基本类型。QML <1> Item 布局 属性
Item {
Layout.fillWidth: true
Layout.fillHeight: true
}
2.行 Component
Loader 加载各列Component 并用RowLayout 布局
代码如下(示例):
Component
{
id:rowDelegate
Rectangle
{
id:listViewItem
width: parent.width
height: 40
color: index === listView.currentIndex ? "lightgray" : "white"
RowLayout
{
anchors.fill: parent
spacing: 0
Loader {
id: columnRole1
property string column_text: column_role_1
Layout.preferredWidth:header_data[0].width_ratio * parent.width
Layout.preferredHeight: parent.height
anchors.verticalCenter: parent.verticalCenter
sourceComponent: columnRole1Component
}
Loader {
id: columnRole2
property string column_text: column_role_2
Layout.preferredWidth: header_data[1].width_ratio * parent.width
Layout.preferredHeight: parent.height
anchors.verticalCenter: parent.verticalCenter
sourceComponent: columnRole2Component
}
Loader {
id: columnRole3
property string column_text: column_role_3
Layout.preferredWidth: header_data[2].width_ratio * parent.width
Layout.preferredHeight: parent.height
anchors.verticalCenter: parent.verticalCenter
sourceComponent: columnRole3Component
}
}
}
}
3.列 Component
Component
{
id:columnRole1Component
Rectangle
{
anchors.fill: parent
color: "transparent"
border.width: 1
Text
{
anchors.fill: parent
font.family: "Microsoft YaHei"
font.pixelSize: 16
font.weight: Font.Medium
elide: Text.ElideRight
wrapMode: Text.WrapAnywhere
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
clip: true
text: column_text
}
}
}
总结
示例运行结果如下:
说明:列宽均通过Layout.preferredWidth 按表头数据中列比例指定了宽度,仅表头使用item挤压空白