繁体   English   中英

如何将QQuickItem的中心转换为新的中心

[英]How to transform the center of a QQuickItem to a new center

我有一个Qt QML应用程序。 以下是该应用程序的完整代码:

码:

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?
            }
        }
    }
}

题:
我的问题很简单。 如何将任何QQuickitem中心更改为新中心? 因此,在上述情况下my_item_2收到点击事件时 如何my_item_1的中心更改为新的中心( Qt.point(some_x_center,some_y_center) )。 另外 ,能否获得另一个物品的中心? app_main_windowmy_item_2的中心应用于目标my_item_1吗?

PS:
我简化了代码,使问题变得客观。 在我的实际代码中,我有一个非常复杂的逻辑,在这里我需要将my_item_1类的my_item_1重新对齐到一个新的中心,而无需使用锚点,因为我正在尝试使用的QQuickitem被缩放并平移到一个新点。

如果无法使用锚点,则必须手动计算中心并进行分配。

快速示例:

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
        }
    }
}

请注意,这仅是一次移动,并且如果移动目标,则矩形不会移动。

为了使其遵循目标,您必须将其与Qt.binding重新绑定。

如果rectToMove与nonParentOrSibling不在同一坐标系中,则可以使用Item.mapToItem()mapFromItem()来调整坐标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM