Switch.qml 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * Copyright (c) 2011 Nokia Corporation.
  3. */
  4. import QtQuick 1.1
  5. Item {
  6. id: toggleswitch
  7. property bool on: false
  8. property int farX
  9. signal switched(bool on);
  10. function toggle() {
  11. if (toggleswitch.state == "on")
  12. toggleswitch.state = "off";
  13. else
  14. toggleswitch.state = "on";
  15. switched(toggleswitch.on);
  16. }
  17. function releaseSwitch() {
  18. if (knob.x == 1) {
  19. if (toggleswitch.state == "off") return;
  20. }
  21. if (knob.x == toggleswitch.farX) {
  22. if (toggleswitch.state == "on") return;
  23. }
  24. toggle();
  25. }
  26. Image {
  27. id: background
  28. anchors.fill: parent
  29. fillMode: Image.PreserveAspectFit
  30. smooth: true
  31. source: "qrc:/images/btn_back.png"
  32. MouseArea {
  33. anchors.fill: parent;
  34. onClicked: {
  35. toggle();
  36. }
  37. }
  38. }
  39. Component.onCompleted: {
  40. farX = background.width - knob.width
  41. }
  42. Text {
  43. anchors.left: background.left
  44. anchors.leftMargin: 10
  45. anchors.verticalCenter: background.verticalCenter
  46. color:"white"
  47. font.pixelSize: background.height * 0.4
  48. text:"ON"
  49. smooth: true
  50. }
  51. Text {
  52. anchors.right: background.right
  53. anchors.rightMargin: 10
  54. anchors.verticalCenter: background.verticalCenter
  55. color:"white"
  56. font.pixelSize: background.height * 0.4
  57. text:"OFF"
  58. smooth: true
  59. }
  60. Image {
  61. id: knob
  62. height: background.height
  63. width: background.width * 0.5
  64. x: 1;
  65. fillMode: Image.PreserveAspectFit
  66. smooth: true
  67. source: "qrc:/images/back_on-off_active.png"
  68. MouseArea {
  69. anchors.fill: parent
  70. drag.target: knob; drag.axis: Drag.XAxis; drag.minimumX: 1; drag.maximumX: toggleswitch.farX
  71. onClicked: {
  72. toggle();
  73. }
  74. onReleased: {
  75. releaseSwitch();
  76. }
  77. }
  78. }
  79. states: [
  80. State {
  81. name: "on"
  82. PropertyChanges { target: knob; x: toggleswitch.farX }
  83. PropertyChanges { target: toggleswitch; on: true }
  84. },
  85. State {
  86. name: "off"
  87. PropertyChanges { target: knob; x: 1 }
  88. PropertyChanges { target: toggleswitch; on: false }
  89. }
  90. ]
  91. transitions: Transition {
  92. NumberAnimation { properties: "x"; easing.type: Easing.InOutQuad; duration: 200 }
  93. }
  94. }