QML自定义开关Switch

1.QML基本控件Switch

在QtQuick.Controls 2 中,已经有了Qt官方提供的开关控件,而且还带有过渡动画,但是可能颜色有些不美观,研究了一下入如何自定义一个开关以供以后使用
Tips:
要获取开关的状态,可以用 属性:checked 来获取

2.自定义开关控件,改变其样式

首先来看原生样式:
在这里插入图片描述

其源代码为:

    Switch{
        id : switch1
        text: closeState
        onCheckedChanged: {
            switch1.text = switch1.checked ? "WiFI已打开" : "WiFI已关闭"
        }
    }

自定义后的开关:
在这里插入图片描述
源代码:

import QtQuick 2.12
import QtQuick.Controls 2.12

  Switch {
      id: control
      text: qsTr("Switch")

//      background: Rectangle{
//          color: "lightyellow"
//      }

      indicator: Rectangle {
          implicitWidth: 48
          implicitHeight: 26
          x: control.leftPadding
          y: parent.height / 2 - height / 2

          radius: 13
          color: control.checked ? "green" : "#ffffff"
          border.color: control.checked ? "green" : "#cccccc"

          //小圆点
          Rectangle {
              id : smallRect
              width: 26
              height: 26
              radius: 13
              color: control.down ? "#cccccc" : "#ffffff"
              border.color: control.checked ? (control.down ? "#17a81a" : "#21be2b") : "#999999"

			//改变小圆点的位置
              NumberAnimation on x{
                  to: smallRect.width
                  running: control.checked ? true : false
                  duration: 200
              }

			//改变小圆点的位置
              NumberAnimation on x{
                  to: 0
                  running: control.checked ? false : true
                  duration: 200
              }
          }
      }

	  //要显示的文本
      contentItem: Text {
          text: control.checked.toString()
          font.pixelSize: 50
          //鼠标按下时  control.down
          color: control.down ? "green" : "red"
          verticalAlignment: Text.AlignVCenter
          anchors.left: indicator.right
      }
}

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值