![](https://img-blog.csdnimg.cn/img_convert/604427523d3327e7cd017bac1acc0c60.gif)
在滚动翻页和拖动翻页时,一次翻一整页。
CustomScrollBar.qml
import QtQuick 2.12
Rectangle {
id: custscrollbar
anchors.right: list.right
anchors.top: list.top
width: 10
height: list.height
color: "lightgreen"
clip: true
Rectangle {
id: btn
y: list.visibleArea.yPosition * custscrollbar.height
width: 10
height: list.visibleArea.heightRatio * custscrollbar.height
color: "green"
radius: 20
}
MouseArea {
id: mousearea
anchors.fill: custscrollbar
//使得按钮可以上下拖动
drag.target: btn
drag.axis: Drag.YAxis
drag.minimumY: 0
drag.maximumY: list.height - btn.height
// 拖动
onMouseYChanged: {
//一次翻一整页
var ypos = btn.y / list.height * list.contentHeight;
var curPage = Math.round(ypos/list.pageHeight) //当前所在的页数(四舍五入取整数)
list.curPageIndex = curPage
}
}
}
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
ListModel {
id: lmodel
}
ListView {
id: list
property int curPageIndex: 0 //当前所在页
//项高
property int itemHeight: 30
// 一页的高度
property int pageHeight: Math.trunc(list.height/list.itemHeight)*list.itemHeight
// 页数
property int pageNum: Math.trunc(list.contentHeight/list.pageHeight)
model: lmodel
width: 300
height: parent.height
interactive: false //禁用默认的滚动和拖动
delegate: Rectangle{
color: "lightblue"
width: 300
height: list.itemHeight
border.width: 1
border.color: "gray"
Text {
text: index
anchors.centerIn: parent
color: "red"
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
}
MouseArea {
anchors.fill: list
onWheel: {
if(wheel.angleDelta.y > 0){
//向上滚
list.pageUp()
}else{
//向下滚
list.pageDown()
}
}
}
CustomScrollBar {
id: custscrollbar
}
onCurPageIndexChanged: {
list.contentY = list.curPageIndex*list.pageHeight
}
function pageUp() {
if(curPageIndex > 0){
--curPageIndex
}
}
function pageDown() {
if(curPageIndex < pageNum){
++curPageIndex
}
}
}
Component.onCompleted: {
for(var i = 0; i< 500; ++i){
lmodel.append({"index": i})
}
}
}