在QML中,mapToItem 与 mapFromItem 经常用于坐标转换。
mapToItem(item, real x, real y) 将(x,y)映射到item所在的坐标系,返回映射后的点。其中,(x,y)是在调用该方法的对象系统中的坐标。
mapFromItem(item, real x, real y) 将item所在的坐标系中的(x,y)点映射到,调用对象所在的坐标系,返回映射后的点。其中,(x,y)是在item对象系统中的坐标。
//将item1所在坐标系中的(x,y)映射到item所在的坐标系中,返回映射后的点
object pos = item1.mapToItem(item, real x, real y)
//将item所在坐标系中的(x,y)点映射到item1所在的坐标系,返回映射后的点。
object pos = item1.mapFromItem(item, real x, real y)
如果函数参数中的item为null的话,那么坐标点的转换是基于QML view的根组件的。
示例:
import QtQuick 2.15
Window {
id: root
visible: true
width: 1000
height: 480
title: qsTr(