Qml 映射全局坐标不正确

问题描述 投票:0回答:1

在此代码部分中,我创建了内部包含窗口和矩形的简单示例。我为矩形设置 x = 100 和 y = 100 内部坐标。当我将这些坐标映射到全局并得到不正确的结果时,坐标总是比实际坐标多 2 倍。例如,如果我将 x 和 y 设置为 50,则结果将为 50*2 = 100。为什么会出现错误?我该如何解决它?

    import QtQuick 2.15
    import QtQuick.Window 2.15
    
    Window {
        id: root
    
        width: 640; height: 480; visible: true;
        title: qsTr("Hello World")
        onXChanged: innerRect.globalChanged();
        onYChanged: innerRect.globalChanged()
        onWidthChanged: innerRect.globalChanged();
        onHeightChanged: innerRect.globalChanged()
    
        Rectangle {
            id: innerRect
    
            signal globalChanged()
            property point globalPoint
            onGlobalChanged: {
                innerRect.globalPoint = mapToGlobal(innerRect.x, innerRect.y)
            }
            color: "yellow"
            width: parent.width / 2; height: parent.height / 2
    
            x: 100; y: 100
    
            Text {
                id: xCoord
    
                anchors.left: parent.left;
                anchors.leftMargin: 20
                anchors.verticalCenter: parent.verticalCenter
                text: "Gx: " + innerRect.globalPoint.x + " Wx: " + root.x
            }
            Text {
                id: yCoord
    
                anchors.right: parent.right;
                anchors.rightMargin: 20
                anchors.verticalCenter: parent.verticalCenter
                text: "Gy: " + innerRect.globalPoint.y + " Wy: " + root.y
            }
        }
    }

qt qml
1个回答
0
投票

您正在使用不正确的参数调用

mapToGlobal
。文档说:

将该项坐标系中的点 (x, y) 映射到全局坐标系,并返回与映射坐标相匹配的点。

在您的代码中,您将相对于矩形坐标系的 100, 100 点映射到全局坐标系。如果你想映射矩形的左上角点,只需调用

mapToGlobal(0,0)
即可。请记住,
mapToGlobal
是一个成员函数,因此您在代码中调用
innerRect.mapToGlobal(innerRect.x, innerRect.y)

© www.soinside.com 2019 - 2024. All rights reserved.