下面的应用程序输出从一个 QQuickItem
映射的坐标到另一个。根据文档:
object mapToItem(Item item, real x, real y)
Maps the point (x, y) or rect (x, y, width, height), which is in this item's coordinate system, to item's coordinate system, and returns an object with x and y (and optionally width and height) properties matching the mapped coordinate.
我希望输出是这样的:
0 0
1 1
2 2
但我得到:
QPointF(9, 6) 100
QPointF(9, 5) 100
QPointF(8, 5) 100
为什么是
mapped.x
的类型QPointF
?我希望它是一个浮点值。什么是实际mapped
类型?import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
width: 640
height: 480
Rectangle {
anchors.fill: parent
id: r0
color: "green"
Rectangle {
x: 50; y:100; width: 100; height: 100;
id: r
color: "yellow"
MouseArea {
id: mousearea
anchors.fill: parent
hoverEnabled: true
onPositionChanged: {
var mouseP = Qt.point(mouse.x, mouse.y);
var mapped = r.mapToItem(r0, mouseP);
console.log(mapped.x, ' ', mapped.y);
}
}
}
}
}
更新 1: QQuickItem有
mapToItem
带有 2 个参数和 Item有 mapToItem
有 3 个参数。上面代码中调用的是哪一个?
最佳答案
在您的情况下,mapToItem
需要 3 个参数。您无需先创建点。
onPositionChanged: {
var mapped = r.mapToItem(r0, mouse.x, mouse.y);
console.log(mapped.x, ' ', mapped.y);
}
背景说明 : 这似乎是一个错误,我只是 reported .
您的代码调用 QQuickItem::mapToItem() 有两个原因。一、
QQuickItem::mapToItem(const QQuickItem *item, const QPointF &point) const;
不是 INVOKABLE,即它没有从 C++ 暴露给 QML。二、QQuickItem::mapToItem(const QQuickItem *item, const QPointF &point) const;
返回 QPointF
直接谁的内部属性叫xp
和 yp
而不是 x
和 y
(这可以使用调试器观察到)。在
QQuickItem::mapToItem()
x
和 y
被 C++ 强制为 qreal
类型,这是 C++ double
的别名.偶if (v = (*args)[1])->asDouble()
完全吓坏了,x
必须是在您的情况下,它应该是
NaN
. y = 0
因为没有设置参数 3。因此点 (NaN, 0)
被 build 。从那时起,其余的计算没有任何意义,但缺少错误处理。从 Qt 5.2 开始使用了一个新的 JavaScript 引擎。在 5.1 及之前,使用 V8,返回
NaN
而不是 QPointF
到 QML。
关于qt - QQuickItem::mapToItem 返回类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001124/