PDA

View Full Version : QML Toggle Button



ChriD
26th January 2016, 12:17
Hi,
I want to create a toggle button like this one
http://i.stack.imgur.com/Tb2aV.png
My first approach doesn't work propper and i dont know why.
The first toggle seems to be okay, but the second one fills the whole toggle area instead of "moving" the child rectangle back to the right Position.
What would be the best approach to create such toggle button?



Rectangle {
id: root
property alias label: text.text
property bool active: false

signal toggled
height: 30
width: height * 2.5
radius: height * 0.25
color: "lightgray"
border.width: 1
border.color: "#11000000"
Text { id: text; anchors.centerIn: parent; font.pixelSize: 14; }
MouseArea {
anchors.fill: parent
onClicked: { active = !active; root.toggled() }
}

Item{
width: parent.width * 0.75
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.right: active ? undefined : parent.right
anchors.left: active ? parent.left : undefined
Rectangle {
anchors.fill: parent
radius: root.height * 0.25
color: active ? "green" : "red"
}
}
}



Thanks!

Added after 5 minutes:

Okay. i found another solution. I use the margind isntead of the anchors left and right



Rectangle {
id: root
//property alias label: text.text
property bool active: false

signal toggled
height: guiTheme.app.standardTextSize * 1.25
width: height * 2.5
radius: height * 0.25
color: "lightgray"
border.width: 1
border.color: "#11000000"
//Text { id: text; anchors.centerIn: parent; font.pixelSize: 14; }
MouseArea {
anchors.fill: parent
onClicked: { active = !active; root.toggled() }
}

Item{
//width: parent.width * 0.75
anchors.top: parent.top
anchors.bottom: parent.bottom
//anchors.right: active ? undefined : parent.right
//anchors.left: active ? parent.left : undefined
anchors.right: parent.right
anchors.left: parent.left
anchors.leftMargin: active ? 0 : (parent.width * 0.25)
anchors.rightMargin: active ? (parent.width * 0.25) : 0
Rectangle {
anchors.fill: parent
radius: root.height * 0.25
color: active ? "green" : "red"
}
}

}


That works...

anda_skoa
26th January 2016, 12:23
There is also QtQuick.Controls Switch http://doc.qt.io/qt-5/qml-qtquick-controls-switch.html

You could also emit the toggled signal when active changes, unless you only want it to be emitted when the change is affected by the click.

Cheers,
_

ChriD
26th January 2016, 12:37
I completely missed that! Thank you for your info. Of course i'll use the Switch withSytling Component instead my poor attempt :)