TheWaterProgrammer
TheWaterProgrammer

Reputation: 8229

How to transform the center of a QQuickItem to a new center

I have a Qt QML application. Following is the complete code of the application:

Code:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    id: app_main_window
    visible: true
    width: 800
    height: 600
    title: qsTr("Hello QML")

    Rectangle {
        id: my_item_1
        x: 100
        y: 100
        width: 100
        height: 100
        color: "grey"
        visible: true
        z: 1
    }

    Rectangle {
        id: my_item_2
        x: 400
        y: 400
        width: 100
        height: 100
        color: "grey"
        visible: true
        z: 1

        MouseArea {
            anchors.fill: parent
            onClicked: {
                // How can I change the center of my_item_1  to some arbitrary new center. lets say app_main_window's center. this involves another question. how can I get app_main_window's center?
            }
        }
    }
}

Question:
My question is simple. How can change the center of any QQuickitem to a new center? So in above case how can change the center of my_item_1 to a new center (Qt.point(some_x_center, some_y_center)) when my_item_2 gets a click event. Additionally, is possible to get another item's center? Like app_main_window or my_item_2's center to apply to the target my_item_1?

PS:
I have made the code simple to make the question objective. I have quite a complicated logic in my actual code where I need to realign something like my_item_1 to a new center without usage of anchors as the QQuickitem I am trying to do that with is scaled and panned into a new point.

Upvotes: 0

Views: 1315

Answers (1)

dydil
dydil

Reputation: 997

If anchors can't be used, you have to calculate manually the center and assign it.

Quick example:

Item
{
    anchors.fill: parent

    Rectangle
    {
        id: nonParentOrSibling
        width: 200
        height: 200
        x: 350
        y: 240
        color: "red"
    }

}

Rectangle
{
    id: rectToMove

    width: 100
    height: 100
    y: 200
    color: "blue"

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            var itemCenter = Qt.point(nonParentOrSibling.x + nonParentOrSibling.width / 2, nonParentOrSibling.y + nonParentOrSibling.height / 2)
            rectToMove.x = itemCenter.x - rectToMove.width / 2
            rectToMove.y = itemCenter.y - rectToMove.height / 2
        }
    }
}

Note that this is a one time moving only, and the rectangle won't move if the target is moved.

To make it follow the target you have to rebind it with Qt.binding.

If rectToMove is not in the same coordinate system as nonParentOrSibling, you can use Item.mapToItem() and mapFromItem() to adapt the coordinates.

Upvotes: 1

Related Questions