QML小例子:带固定标题栏的列表
一开始,先看下最终的效果
列表正常显示效果
列表滑动之后,上方的标题栏固定在顶部
下面贴上代码:
import QtQuick 2.6
import QtQuick.Window 2.2
Window {
id: root
visible: true
width: 640
height: 720
title: qsTr("Hello World")
Rectangle {
width: parent.width
height: 50
color: "#000000"
visible: listView.contentY >= -50
z: 10
Text {
anchors.verticalCenter: parent.verticalCenter
x: 15
text: "编号"
font.pixelSize: 20
color: "#ffffff"
}
Text {
anchors.verticalCenter: parent.verticalCenter
x: 360
text: "标题"
font.pixelSize: 20
color: "#ffffff"
}
}
ListView {
id: listView
width: parent.width
height: parent.height
model: 20
clip: true
header: Component {
Item {
width: listView.width
height: 180
Rectangle {
width: listView.width
height: 130
color: "#990000ff"
Text {
anchors.centerIn: parent
text: "xxxxxx信息展示"
font.pixelSize: 30
color: "#ffffff"
}
}
Rectangle {
y: 130
width: listView.width
height: 50
color: "#000000"
Text {
anchors.verticalCenter: parent.verticalCenter
x: 15
text: "编号"
font.pixelSize: 20
color: "#ffffff"
}
Text {
anchors.verticalCenter: parent.verticalCenter
x: 360
text: "标题"
font.pixelSize: 20
color: "#ffffff"
}
}
}
}
delegate: Component {
Rectangle {
height: 130
width: root.width
color: "#88ffff00"
Text {
anchors.verticalCenter: parent.verticalCenter
x: 15
text: index
font.pixelSize: 20
color: "#ff0000"
}
Text {
anchors.verticalCenter: parent.verticalCenter
x: 250
text: "xxxxxxxxxxxxxxxxxxxxxxxx"
font.pixelSize: 20
color: "#ff0000"
}
Rectangle {
anchors.bottom: parent.bottom
width: parent.width
height: 2
color: "#000000"
}
}
}
}
}
在实现过程中,其实刚开始的标题栏和滑动之后的标题栏不是同一个,ListView设置head,同时在页面顶部加一个与head相同的Rectangle,在head滑出页面时显示我们的Rectangle,达到了不同标题栏的无缝衔接,判断head是否滑出,根据ListView的contentY来判断。