QML ListView添加滚动条
ListView添加滚动条,利用ScrollBar.horizontal: ScrollBar { id: hbar; active: vbar.active }; ScrollBar.vertical: ScrollBar { id: vbar; active: hbar.active }的方式有问题(水平方向的比较严重)。所以采用另外一种方式。
代码如下
import QtQuick 2.9
import QtQuick.Controls 2.3
/*****************************************************
// 此文件主要实现1. listview添加滚动条,水平方向和竖直方向。2.实现选中的效果
// 实现函数:动态添加数据,清除全部数据。
*****************************************************/
Rectangle{
id : mrect
color: "#ff0000"
width: 200;
height: 200
clip: true
property int listviewwidth: 400
property int listviewheigth: 400
function addElement(ele)
{
dmode.append(ele)
}
function clearData()
{
dmode.clear();
}
//测试动态添加数据
Component.onCompleted:
{
for (var i = 0 ; i< 10;++i)
addElement({"name":"测试完成","mcolor":"#dd0000","number":i+1})
}
/////////////////////////
ListModel
{
id : dmode
}
ListView {
id : listview;
width: listviewwidth;
height: listviewheigth
y : -vbar.position*height
x : -hbar.position*width
model: dmode
delegate: Rectangle
{
color: ListView.isCurrentItem ? "black" : "green" //实现选择效果
border.color: "white"
height : 30;
width : listview.width
border.width : 0
Text {
lineHeightMode : Text.FixedHeight
lineHeight : 30
horizontalAlignment : Text.AlignHCenter
verticalAlignment : Text.AlignVCenter
text: name + number
color: mcolor
}
MouseArea {
anchors.fill: parent
onClicked: listview.currentIndex = index //实现item切换 实现选择效果
}
}
}
ScrollBar {
id: vbar
hoverEnabled: true
active: hovered || pressed
orientation: Qt.Vertical
size: mrect.height/listview.height
anchors.top: parent.top
anchors.right: parent.right
anchors.bottom: parent.bottom
policy: ScrollBar.AlwaysOn
//定义样式
// contentItem: Rectangle {
// implicitWidth: 6
// implicitHeight: 100
// radius: width / 2
// color: vbar.pressed ? "#81e889" : "#c2f4c6"
// }
}
ScrollBar {
id: hbar
hoverEnabled: true
active: hovered || pressed
orientation: Qt.Horizontal
size: mrect.width/listview.width
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
//policy: ScrollBar.AlwaysOn
//定义样式
// contentItem: Rectangle {
// //implicitWidth: 6
// //implicitHeight: 100
// radius: width / 2
// color: hbar.pressed ? "#81e889" : "#c2f4c6"
// }
}
}