[QML]BaseComponentsQML基础自定义控件-ToggleBtn状态切换按钮
效果展示ToggleBtn.qmlimport QtQuick 2.15 import QtQuick.Layouts 1.15 Item { id: root height: 32 // 开关核心接口 property bool checked: true property color bgColorUnchecked: #000000 property color bgColorChecked: #374151 property color borderColor: #6B7280 property color thumbColor: #9CA3AF signal toggled(bool checkedState) // 双向绑定接口 property bool bindValue: true // 标签与状态文字接口 property string labelText: property string checkedText: property string uncheckedText: property color labelColor: #ffffff property color checkedTextColor: #2ecc71 property color uncheckedTextColor: #e74c3c property real labelFontSize: 14 property real statusFontSize: 14 // 布局接口 property real leftPadding: 0 property real rightPadding: 0 property real topPadding: 0 property real contentSpacing: 6 property real switchWidth: 60 property real switchHeight: 32 // 双向绑定同步 onBindValueChanged: { if (checked ! bindValue) { checked bindValue } } // 内部布局 RowLayout { anchors.left: parent.left anchors.right: parent.right anchors.top: parent.top anchors.topMargin: root.topPadding anchors.leftMargin: root.leftPadding anchors.rightMargin: root.rightPadding height: root.switchHeight spacing: root.contentSpacing Text { text: root.labelText color: root.labelColor font.pixelSize: root.labelFontSize font.bold: true Layout.alignment: Qt.AlignVCenter visible: root.labelText ! } Text { text: root.checked ? root.checkedText : root.uncheckedText color: root.checked ? root.checkedTextColor : root.uncheckedTextColor font.pixelSize: root.statusFontSize font.bold: true Layout.alignment: Qt.AlignVCenter visible: root.checkedText ! || root.uncheckedText ! } Rectangle { id: toggleBtn width: root.switchWidth height: root.switchHeight radius: height / 2 border.width: 6 border.color: root.borderColor color: root.checked ? root.bgColorChecked : root.bgColorUnchecked Behavior on color { ColorAnimation { duration: 200 } } Rectangle { id: thumb width: 14 height: 14 radius: width / 2 color: root.thumbColor anchors.verticalCenter: parent.verticalCenter x: root.checked ? (toggleBtn.width - width - 8) : 8 Behavior on x { NumberAnimation { duration: 200; easing.type: Easing.OutQuad } } } MouseArea { anchors.fill: parent cursorShape: Qt.PointingHandCursor onClicked: { root.checked !root.checked root.toggled(root.checked) } } } } }