在Qt帮助文档里
object mapToItem(Item item, real x, real y)
object mapToItem(Item item, real x, real y, real width, real height)
object mapFromItem(Item item, real x, real y)
object mapFromItem(Item item, real x, real y, real width, real height)
其实只要弄清楚
object mapToItem(Item item, real x, real y)
object mapFromItem(Item item, real x, real y)
就全部都弄清楚了。
If item is a null value, this maps the point or rect to the coordinate system of the root QML view.
如果函数参数中的item为null的话,那么坐标点的转换是基于QML view的根组件的。

其中rect1的原点(矩形左上角的点)在根view中的坐标为(5, 5),
rect2的原点(矩形左上角的点)在rect1中的坐标点为(20,20)。
rect2.mapToItem(rect1, 0, 0);
是将rect2中坐标点为(0, 0),转换成rect1中的坐标点。
助记方法: 坐标点(0, 0),在rect2中,要转换成 rect1中的坐标点。
rect2.mapFromItem(rect1, 0, 0);
是将rect1中坐标为(0, 0),转换成rect2中的坐标点。
助记方法: 坐标点(0, 0),从rect1中,要转换成 rect2中的坐标点。
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.5
ApplicationWindow {
id: root
visible: true
width: 300
height: 200
title: qsTr("Hello World")
color: "#C2C2C2"
Rectangle {
id: rect1
x: 5
y: 5
width: parent.width-10
height: 100
color: "#87CEFF"
Label {
text: "rect1"
}
Rectangle {
id: rect2
x: 20
y: 20
width: rect1.width-30
height: 60
color: "#9AFF9A"
Label {
text: "rect2"
}
}//end rect2
}//end rect1
Text {
id: labelShow
text: qsTr("text")
anchors.top: rect1.bottom
anchors.left: rect1.left
anchors.topMargin: 10
font.pixelSize: 12
Component.onCompleted: {
var pos1 = rect2.mapToItem(null, 0, 0);
var msg1 = "rect2.mapToItem(null, 0, 0) x is:" + pos1.x + " y:" + pos1.y + "\n\n";
var pos2 = rect2.mapFromItem(null, 0, 0);
var msg2 = "rect2.mapFromItem(null, 0, 0) x is:" +pos2.x + " y:" + pos2.y + "\n\n";
var pos3 = rect2.mapToItem(rect1, 0, 0);
var msg3 = "rect2.mapToItem(rect1, 0, 0) x is:" + pos3.x + " y:" + pos3.y + "\n\n";
var pos4 = rect2.mapFromItem(rect1, 0, 0);
var msg4 = "rect2.mapFromItem(rect1, 0, 0) x is:" +pos4.x + " y:" + pos4.y + "\n\n";
var msg = msg1 + msg2 + msg3 + msg4;
labelShow.text = msg.toString();
}
}
}
参考:https://blog.youkuaiyun.com/imtina/article/details/53670528

本文详细解析了Qt QML中坐标转换的方法,包括objectmapToItem和objectmapFromItem函数的具体使用方式,并通过实例说明如何进行不同元素间的坐标转换。

726

被折叠的 条评论
为什么被折叠?



