Aquarius_Girl
Aquarius_Girl

Reputation: 22916

Rotating a line without moving it in QML

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?

Upvotes: 0

Views: 2757

Answers (1)

Mitch
Mitch

Reputation: 24406

The origin should be half the width and height of the item that you're rotating if you wish to rotate it about its centre. Note that the dot is not the true origin; I've tweaked your code a bit:

import QtQuick 2.0

Rectangle {
    id: dial
    width: 360
    height: 360

    color: "gray"

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

    Rectangle {
        id: line
        height: 5
        width: 50
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter
        transform: Rotation {
            origin.x: line.width / 2
            origin.y: line.height / 2
            angle: 40
        }
    }
}

rotated line

Or, if you want to get even simpler:

import QtQuick 2.0

Rectangle {
    id: dial
    width: 360
    height: 360
    color: "gray"

    Rectangle {
        id: line
        height: 5
        width: 50
        anchors.centerIn: parent
        rotation: 40
    }

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

Upvotes: 5

Related Questions