天天看點

Qt基于Qml選擇開關示例

 示範效果

Qt基于Qml選擇開關示例
Qt基于Qml選擇開關示例

 切換開關元件實作QML

import QtQuick 2.12

Rectangle {
    id: root
    width: 80
    height: 26
    color: "#EAEAEA"
    radius: 13

    property string leftString
    property string rightString
    signal toggleLeft //左開關信号
    signal toggleRight //右開關信号

    Rectangle {
        id: rect
        width: parent.width * 0.6
        radius: parent.radius
        color: rect.state === "left"? "#FF00FF" : "#CCCCCC" //根據狀态切換背景色
        state: "left"
        anchors {
            top: parent.top
            bottom: parent.bottom
        }

        states: [
            State {
                name: "right"
                PropertyChanges {
                    target: rect
                    x: root.width - rect.width
                }
            }

        ]

        transitions: [
            Transition {
                from: "*"
                to: "*"
                NumberAnimation { property: "x"; duration: 200 }
            }
        ]

        Text {
            id: label
            anchors.centerIn: parent
            text: rect.state === "left"? root.leftString : root.rightString
            color: "white"
            font.pointSize: 10
        }
    }

    MouseArea {
        anchors.fill: parent
        onPressed: {
            //點開切換狀态
            if(rect.state === "left"){
                rect.state = "right";
                root.toggleRight();
            }else {
                rect.state = "left";
                root.toggleLeft();
            }
        }
    }
}      
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
    visible: true
    width: 400
    height: 300
    title: qsTr("Qt基于Qml選擇開關示例")
    Label{
        id: label
        anchors.bottom: qmlToggleButton.top
        anchors.horizontalCenter: parent.horizontalCenter
        height: 24
        width: contentWidth
    }
    ToggleButton{
        id: idToggleButton
        anchors.centerIn: parent
        height: 38
        width: 100
        leftString: qsTr("打開")
        rightString: qsTr("關閉")
        onToggleLeft: label.text = idToggleButton.leftString
        onToggleRight: label.text = idToggleButton.rightString
    }
}