QML亮度调节滑动条

功能:鼠标点住后上下拖动,实现进度条滑动,可以用于实现触摸屏幕上的亮度调节按钮或音量调节按钮。

实现思路

1、首先画一个矩形记为Rect1,设置颜色为白色,作为根矩形
2、画一个跟矩形Rect1大小一致的矩形Rect2,Rect2的透明度设置为透明,主要用于拖动
3、画一个Rect3跟Rect1大小一致,颜色为绿色,主要用来显示进度。
4、Rect2移动后的位置Rect2.y 跟当前的位置curY求差:dist = curY - Rect2.y, 有了dist后,可以计算Rect3的高度:Rect3.height = Rect3.height + dist,时时更新
5、松开鼠标后,Rect2必须恢复到原位置:Rect2.y = 0,以便于下次触摸计算。

详细的实现细节,请见代码注释

实现代码

SlideBar.qml

import QtQuick 2.5

Rectangle{
    id:scrollbarRoot   //矩形1,作背景
    color: "white"
    radius: 10
    property int percent: 0  
    property int curY: 0  // 定义局部变量,存储上一次change时的y的值

    Rectangle{
        id: button  // 矩形2 用于鼠标点击后滑动
        anchors.left: parent.left // 千万不要设置anchors.fill, anchors.top, anchors.bottom,这样操作后无法上下滑动 
        width: parent.width // 宽度高度跟背景框保持一致
        radius: parent.radius
        height: parent.height
        smooth: true 
        color:"black"
        z:100  // z必须设置,这样保证该矩形位于最上方,用于点击滑动
        opacity: 0
        MouseArea {
            id:ma
            anchors.fill: button  // 整个区域都可以点击滑动
            drag.target: button
            drag.axis: Drag.YAxis  // 设置滑动轴为Y轴
            drag.minimumY: -1 * scrollbarRoot.height // 滑动的最小值,即向上最多能滑动多大,这里设置的是一个height
            drag.maximumY: scrollbarRoot.height // 滑动的最大值,即向下最多能滑动多大,这里设置的是一个height
            onMouseYChanged:{ // 图像y坐标移动时响应处理
                var tmp = (scrollbarRoot.curY - button.y) // 计算移动值
                tmp += fillRect.height // 移动值加到滑动条的高度
                if (tmp > scrollbarRoot.height) { // 滑动条高度的上下限设置 [0, height]
                    tmp = scrollbarRoot.height;
                } else if (tmp < 0) {
                    tmp = 0;
                }
                console.log(tmp)
                fillRect.height = tmp; // 真实高度设置
                percent = fillRect.height / scrollbarRoot.height // 计算百分比
                scrollbarRoot.curY = button.y // 更新当前y值
            }

            onReleased : { // 松开处理
                scrollbarRoot.curY = 0; // 松开后,更新当前y值
                button.y = 0;  // 将滑动的矩形恢复到原位置,以便于下一次的点击滑动
            }
        }
    }

    Rectangle {
        id: fillRect  // 进度显示矩形,颜色为绿色
        anchors.bottom: parent.bottom // 不要设置anchors.top,不然无法滑动
        anchors.left: parent.left
        width: parent.width
        height: 0
        radius: parent.radius
        color: "green"
        z:100
    }
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQml 2.12
//import "./base/*.qml"

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
	SlideBar {
        id: slide
        anchors.centerIn: parent
        width: 100
        height: 200
        border.color: "black"
        visible: true
    }
}
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值