C

Qt Quick Ultralite swipe_game Demo

// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial

import QtQuick 2.0
import StyleModule 1.0

/*
    This component provides a switch with a label next to it.
*/

Item {
    id: root

    // NOTE: overwrite the Style value assignments if you want to use the component outside of this project

    property alias font: label.font
    property color textColor: Style.colorText
    property color backgroundBorderColor: Style.colorLines
    property int borderWidth: Style.lineSize
    property color backgroundColor: checked ? Style.colorHighlight : Style.colorPageBackground
    property color handleBorderColor: Style.colorText
    property color handleColor: switchArea.pressed ? Style.colorHighlight : Style.colorPageBackground
    property int radius: Style.buttonRadius
    property int handleAnimationDuration: Style.animationDuration

    property bool checked: false
    property alias text: label.text

    signal triggered()

    implicitHeight: Style.buttonHeight
    implicitWidth: Math.max(height * 2, label.width + Style.buttonTextMargins + switchArea.width)

    Text {
        id: label

        anchors {
            left: parent.left
            verticalCenter: parent.verticalCenter
        }
        color: root.textColor
        text: "Label"
    }

    MouseArea {
        id: switchArea

        anchors {
            right: parent.right
            top: parent.top
            bottom: parent.bottom
        }
        width: height * 2

        onClicked: root.triggered()

        Rectangle {
            id: switchBackground

            anchors.fill: parent
            radius: root.radius
            color: root.backgroundBorderColor

            Rectangle {
                anchors {
                    fill: parent
                    margins: root.borderWidth
                }
                radius: root.radius
                color: root.backgroundColor
            }
        }

        Rectangle {
            id: switchHandle

            anchors {
                top: parent.top
                bottom: parent.bottom
            }
            width: height

            x: root.checked ? parent.width - width : 0
            radius: root.radius
            color: root.handleBorderColor

            Behavior on x {
                NumberAnimation { duration: root.handleAnimationDuration }
            }

            Rectangle {
                anchors {
                    fill: parent
                    margins: root.borderWidth
                }
                radius: root.radius
                color: root.handleColor
            }
        }
    }
}