1. 程式人生 > >QML之實現滾動條

QML之實現滾動條

Scrolbar.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
 
// 滾動條
Rectangle {
    id: scrollbar;
    opacity: 0
    // 繫結到ListView元件
    property ListView target : ListView{}
 
    width: 15; height: target.height;
    anchors.right: parent.right
    color: "#ccbfbf";radius: 10;clip: true;
    // 按鈕
    Rectangle { id: button; x: 0; y: listviewer.visibleArea.yPosition * scrollbar.height;
        width: 15; height: listviewer.visibleArea.heightRatio * scrollbar.height;
        color: "#6D665C"; radius: 10;
        Text{ text:"☰";anchors.centerIn: parent}
 
        // 滑鼠區域
        MouseArea {id: mouseArea;anchors.fill: button
            drag.target: button;drag.axis: Drag.YAxis;drag.minimumY: 0;drag.maximumY: scrollbar.height - button.height
            onPressed: {button.color = "#A4D3EE";fadeIn.start();}
            onReleased: {button.color = "#6D665C";fadeOut.start();}
            // 拖動
            onMouseYChanged: {
                target.contentY = button.y / scrollbar.height * listviewer.contentHeight
            }
        }
    }
    // 移動時顯隱滾動軸
    Connections{
        target: scrollbar.target
 
        onMovingVerticallyChanged: {
            if (target.movingVertically)
                fadeIn.start();
            else
                fadeOut.start();
        }
        onMovingHorizontallyChanged: {
            if (target.movingHorizontally)
                fadeIn.start();
            else
                fadeOut.start();
        }
    }
    NumberAnimation { id:fadeIn;  target: scrollbar; properties: "opacity"; duration: 500; from:0; to:1 }
    NumberAnimation { id:fadeOut; target: scrollbar; properties: "opacity"; duration: 500; from:1; to:0 }
}

使用

Scroolbar{
    target: listviewer//這是一個listview
}

原文連結:https://blog.csdn.net/cqltbe131421/article/details/71600928