[SOLVED] Is there any easy way to rotate an element with mouse?



  • Lets say I have a clock and I want to be able to rotate its hands with mouse. Is it possible with QML only?


  • Moderators

    Shouldn't be too hard. You might look at "this thread":/forums/viewthread/21118 for some inspiration.



  • Thanks mlong, I'll take a look at that.

    EDIT--------------------

    It helped me a lot. I made a small working example, but I have further questions:

    1. At the moment starting rotation (what I see after I start the program) depends on mouse area size. How can I modify the code to start rotation from 0 and change it after mouse click?

    2. Is there a way to rotate an element every specific angle, not continuously? Something like seconds hand in watches.

    My code:
    @// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
    import QtQuick 1.1

    Rectangle {
    id: root
    width: 360
    height: 360
    Rectangle {
    id: tomatorect
    width: 60
    height: 60
    color: "tomato"
    anchors.centerIn: parent
    rotation: if (mouse_area1.angle < 0)
    mouse_area1.angle * 180 / Math.PI + 360
    else
    mouse_area1.angle * 180 / Math.PI
    smooth: true
    }
    MouseArea {
    id: mouse_area1
    anchors.fill: parent
    property real truex: mouseX-root.width/2
    property real truey: root.height/2-mouseY
    property real angle: Math.atan2(truex, truey)
    }
    Text {
    id: rotation
    text: "Rotation: " + tomatorect.rotation
    anchors {
    horizontalCenter: parent.horizontalCenter
    bottom: parent.bottom
    bottomMargin: 20
    }
    }
    }@

    Short video:
    http://youtu.be/IF7fGmtSPHw



  • OK, I've got it working in the way I wanted. Example code below. Maybe someone will find it useful. :)

    @Rectangle {
    id: root
    width: 360
    height: 360
    Rectangle {
    id: tomatorect
    width: 20
    height: 80
    color: "tomato"
    anchors.centerIn: parent
    rotation: 0
    smooth: true
    }
    MouseArea {
    id: mouse_area1
    anchors.fill: parent
    property real truex: mouseX-root.width/2
    property real truey: root.height/2-mouseY
    property real angle: Math.atan2(truex, truey)
    property real strictangle: parseInt(angle * 180 / Math.PI)
    property real modulo: strictangle % 10 /* rotation "jump" 10 degrees /
    onPositionChanged: if (mouse_area1.angle < 0)
    tomatorect.rotation = strictangle - modulo + 360
    else
    tomatorect.rotation = strictangle - modulo + 10 /
    prevent skipping 180 degrees */
    }
    TextInput {
    id: rotation
    text: tomatorect.rotation
    anchors {
    horizontalCenter: parent.horizontalCenter
    bottom: parent.bottom
    bottomMargin: 10
    }
    }@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.