【问题标题】:How to transform the center of a QQuickItem to a new center如何将 QQuickItem 的中心转换为新中心
【发布时间】:2018-02-19 21:22:44
【问题描述】:

我有一个 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 之类的东西重新对齐到一个新的中心,因为我试图这样做的QQuickitem 被缩放并平移到一个新点。

【问题讨论】:

  • 如果您在 QML 中讨论,请查看 anchors 属性。对于实现,您将使用MouseAreaonClicked 以及my_item_1.anchors.centerIn: app_main_window。这是你要找的吗?
  • anchors.centerIn 有什么问题?
  • @dydil 一个潜在的问题是你只能使用带锚的父级或兄弟级。
  • @dydil 正如我所说。如果我可以更改my_item_1 的中心,我有一个不同的问题可以解决。此示例只有代码足以说明问题。

标签: qt qml qtquick2 qquickitem


【解决方案1】:

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

快速示例:

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() 来调整坐标。

【讨论】:

  • 好的。我必须手动计算项目中心。这是我所期待的。感谢你的回答。试试看
猜你喜欢
  • 2014-04-22
  • 2012-01-12
  • 2012-07-13
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
相关资源
最近更新 更多