此範例展示如何以 QML 創建可重用開關組件。
可以找到此範例的代碼在
$QTDIR/examples/declarative/ui-components/slideswitch
目錄。
The elements that compose the switch are:
on
property (the interface to interact with the switch),
toggle()
and
dorelease()
),
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:
Item { Switch { id: mySwitch on: true } Text { text: "The switch is on" visible: mySwitch.on == true } }
the text will only be visible when the switch is on.
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
擁有
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
特性為
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
onReleased
特性。
定義開關的 2 種狀態:
x
position is 78) and the
on
特性為
true
.
x
position is 1) and the
on
特性為
false
.
有關狀態的更多信息,見 QML States .
為開關添加 2 個 JavaScript 函數:
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.
有關腳本的更多信息,見 集成 JavaScript .
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.
有關過渡的更多信息,見 QML Animation and Transitions .
可以在 QML 文件中使用開關,像這樣: