效果展示:
自制开关按钮
整体代码:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.1
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Layouts 1.0
Item{
id:switchBtnRoot
implicitWidth: 60
implicitHeight: 20
//用于判断开关状态,外界可获取该状态值进行响应
property bool isOpen: false
Rectangle{
id:bg
anchors.fill: parent
radius: switchBtnRoot.width/2
state: !isOpen ? "close" : "open"
property alias opentxtVis: openText.visible
property alias closetxtVis: closeText.visible
Text{
id:openText
anchors.verticalCenter: bg.verticalCenter
anchors.left: bg.left
anchors.leftMargin: 8
text: "ON"
color: "#F6F6F6"
font.pixelSize: bg.height * 0.6
visible: opentxtVis
}
Text{
id:closeText
anchors.verticalCenter: bg.verticalCenter
anchors.right: bg.right
anchors.rightMargin: 8
text: "OFF"
color: "#F6F6F6"
font.pixelSize: bg.height * 0.6
visible: closetxtVis
}
states: [
State {
name: "close"
PropertyChanges {
target: bg
color:"#949599"
opentxtVis:false
closetxtVis:true
}
},
State {
name:"open"
PropertyChanges {
target: bg
color:"#46C636"
opentxtVis:true
closetxtVis:false
}
}
]
Rectangle{
id:slider
x:bg.x
anchors.verticalCenter: bg.verticalCenter
width: bg.height
height: width
radius: width/2
color: "#F6F6F6"
border.color:"#7D8184"
border.width:1
NumberAnimation on x{
id:openAnim
from: 0
to:bg.width-slider.width
duration: 250
running: isOpen
loops: 1
}
NumberAnimation on x{
id:closeAnim
from: bg.width-slider.width
to:0
duration: 250
running: false
loops: 1
}
}
MouseArea{
anchors.fill: parent
onClicked: {
switchBtnRoot.isOpen = !switchBtnRoot.isOpen
if(bg.state === "close"){
closeAnim.start()
}
}
}
}
}