buttonqmlswipeqtquick2

Swipeable button in QML


i wanna create a component which can slide a rectangle from left to right to simulate ON or OFF like a iOS left-to-right button to shutdown phone (https://youtu.be/qEJ5PerUqFw?t=42 second 40 like this). Do you know how can I do this ?

Best regard

I try to use Slider and SwipeDelegate components.


Solution

  • In QML, you can create whatever you want, but you should stick to standard controls because they are understandable and familiar to users. If you still want to create some kind of custom control, you can create something like this:

    import QtQuick
    import QtQuick.Controls
    
    Window {
        id: window
        visible: true
        width: 600
        height: 400
        title: "Slider test"
    
        Rectangle {
            id: container
            anchors.centerIn: parent
            width: 300
            height: 50
            radius: 25
            color: "lightgrey"
            border.color: "grey"
            signal myEvent(bool isOn)
    
            Rectangle {
                id: draggableRect
                width: 50
                height: 48
                radius: 25
                color: "orange"
                border.color: "grey"
    
                x: 1
                y: 1
    
                MouseArea {
                    id: dragArea
                    anchors.fill: parent
                    drag.target: parent
                    drag.axis: Drag.XAxis
                    drag.maximumX: 250
                    drag.minimumX: 0
    
                    onReleased: {
                        if (draggableRect.x < 240)
                        {
                            backAnim.running = true;
                        }
                        else
                        {
                            draggableRect.x = 250;
                            container.myEvent(true);
                        }
                    }
                }
    
                PropertyAnimation { id: backAnim; target: draggableRect; property: "x"; to: 1; duration: 300; onFinished: container.myEvent(false); }
            }
        }
    
    
        Connections {
            target: container
            function onMyEvent(isOn) { console.log(isOn ? "ON" : "OFF"); }
        }
    }