QML Example - Toggle Switch
This example shows how to create a reusable switch component in QML.
The code for this example can be found in the
The elements that compose the switch are:
onproperty (the interface to interact with the switch),
- two images (the background image and the knob),
- two mouse regions for user interation (on the background image and on the knob),
- two states (a on state and a off state),
- two functions or slots to react to the user interation (
- and a transition that describe how to go from one state to the other.
This property is the interface of the switch. By default, the switch is off and this property is
false. It can be used to activate/disactivate the switch or to query its current state.
In this example:
the text will only be visible when the switch is on.
Images and user interaction
First, we create the background image of the switch. In order for the switch to toggle when the user clicks on the background, we add a MouseArea as a child item of the image. A
MouseArea has a
onClicked property that is triggered when the item is clicked. For the moment we will just call a
toggle() function. We will see what this function does in a moment.
Then, we place the image of the knob on top of the background. The interaction here is a little more complex. We want the knob to move with the finger when it is clicked. That is what the
drag property of the
MouseArea is for. We also want to toggle the switch if the knob is released between state. We handle this case in the
dorelease() function that is called in the
We define the two states of the switch:
- In the on state the knob is on the right (
xposition is 78) and the
- In the off state the knob is on the left (
xposition is 1) and the
For more information on states see QML States.
This first function is called when the background image or the knob are clicked. We simply want the switch to toggle between the two states (on and off).
This second function is called when the knob is released and we want to make sure that the knob does not end up between states (neither on nor off). If it is the case call the
toggle() function otherwise we do nothing.
At this point, when the switch toggles between the two states the knob will instantly change its
x position between 1 and 78. In order for the the knob to move smoothly we add a transition that will animate the
x property with an easing curve for a duration of 200ms.
For more information on transitions see QML Animation and Transitions.
The switch can be used in a QML file, like this:
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.