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
      }
}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐