PDA

View Full Version : Rotating a line without moving it in QML



TheIndependentAquarius
5th June 2014, 11:10
import QtQuick 2.0

Item
{
width: 660
height: 660

Rectangle
{
id : dial
width: 360
height: 360

color: "gray"

Rectangle
{
id: dot
height: 5
width: 5
color: "red"
x: dial.x + (dial.width/2);
y: dial.y + (dial.height/2);
}

Image
{
id: line
source: "/home/.../documents/test/straightLine.jpg"
height: 50
width: 50
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
transform: Rotation
{
origin.x: dial.x + (dial.width/2);
origin.y: dial.y + (dial.height/2);
angle: 40
}
}
}
}

The dot is a representation of the origin point. The line's center point should stay at that origin.

When I apply the angle : 40, the line moves away from its origin.

How to tell it to say at that origin while rotating?

wysota
5th June 2014, 12:01
Use anchors instead of specifying x and y of all elements directly. And use the "rotation" property instead of applying a Rotation element. The latter is useful if you want to transform around an arbitrary point instead of "transformationOrigin".

You probably want:

import QtQuick 2.0

Item
{
width: 660
height: 660

Rectangle
{
id : dial
width: 360
height: 360

color: "gray"

Rectangle
{
id: dot
height: 5
width: 5
color: "red"
anchors.centerIn: parent
}

Image
{
id: line
source: "/home/.../documents/test/straightLine.jpg"
height: 50
width: 50
anchors.centerIn: parent
rotation: 40
}
}
}

TheIndependentAquarius
5th June 2014, 12:10
Quite thankful to you. That indeed works easily.

I'd be more grateful though if you could explain what was wrong with my code too.

wysota
5th June 2014, 12:31
"x" and "y" are defined relatively to the parent. Thus you cannot reference other item's "x" and "y" values as they are in a different coordinate system. This is similar to:

Item {
id: i1
x: 10
Item {
id: i2
x: 10
}
}

Item "i2" has an absolute x value set to 20 as it is translated by 10 relative to its parent. If instead you do:
Item {
id: i1
x: 10
Item {
id: i2
x: parent.x+10
}
}

Then i2.x == 20 and thus the absolute value is 30 and not 20.

In your code the transformation origin should be set to:

origin.x: line.width/2;
origin.y: line.height/2;

which is equivalent to setting transformOrigin to Item.Center (which is the default).

TheIndependentAquarius
5th June 2014, 12:57
Thankful to you again.