QML中mapToItem和mapFromItem的区别

mapFromItem

object mapFromItem(Item item, real x, real y)

将参数item(A)的坐标系统的坐标点(x,y)映射到调用该方法的对象(B)坐标系统中,并返回一个映射之后的坐标(point)。此时,参数x,y是指的A对象上的坐标点。如果item参数是null值,坐标点的值就是从QML视图的根元素的坐标系统映射出来的。

object mapFromItem(Item item, real x, real y, real width, real height)

将参数item(A)的坐标系统的区域(x,y,width,height)映射到调用该方法的对象(B)的坐标系统中,并返回一个映射之后的区域(rect)。此时,参数x,y,width,height是指来自的A对象的区域。如果item参数是null值,坐标点的值就是从QML视图的根元素的坐标系统映射出来的。

mapToItem

object mapToItem(Item item, real x, real y)

将调用该方法的对象(C)的坐标点(x,y),映射到参数item(D)的坐标系统中,并返回一个映射之后的坐标(point)。此时,参数x,y是指的C对象上的坐标点。如果item参数是null值,坐标点的值就是从QML视图的根元素的坐标系统映射出来的。

object mapToItem(Item item, real x, real y, real width, real height)

将调用该方法的对象(C)的区域(x,y,width,height),映射到参数item(D)的坐标系统中,并返回一个映射之后的区域(rect)。此时,参数x,y,width,height是指来自的C对象的区域。如果item参数是null值,坐标点的值就是从QML视图的根元素的坐标系统映射出来的。

再看一个使用实例:

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true
    x: 100
    y: 100
    width: 640
    height: 480
    title: qsTr("Test item maps")

    Rectangle {
        id: container

        anchors.fill: parent
        anchors.margins: 20

        border.color: "gray"

        Rectangle {
            id: content
            implicitWidth: 120
            implicitHeight: 120
            color: "#666"

            Text {
                id: posValue
                anchors.centerIn: parent
            }

            MouseArea {
                anchors.fill: parent
                drag.target: content
                drag.minimumX: 0
                drag.maximumX: container.width - content.width
                drag.minimumY: 0
                drag.maximumY: container.height - content.height

                function updateText(){
                    var t,m

                    m = container.mapFromItem(content, 0, 0, 12, 34);

                    t = m.x + "," + m.y + "," + m.width + "," + m.height + "\n"

                    m = container.mapFromItem(null, 0, 0, 12, 34);

                    t += m.x + "," + m.y + "," + m.width + "," + m.height + "\n"

                    m = content.mapToItem(container, 0, 0, 12, 34);

                    t += m.x + "," + m.y + "," + m.width + "," + m.height + "\n"

                    m = content.mapToItem(null, 0, 0, 12, 34);

                    t += m.x + "," + m.y + "," + m.width + "," + m.height

                    posValue.text = t

                }

                onPositionChanged: {
                    updateText()
                }

                Component.onCompleted: updateText()
            }
        }
    }
}

运行效果
起始位置的坐标展示

移动之后的坐标展示

结束位置的坐标展示

从代码以及运行效果,我们可以大概的了解这两个function的使用场景和使用之后的效果。

以上是个人对这两个function的理解,如有不当之处欢迎留言指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值