QGraphicsItem::scenePos() 总是返回QPointF(0,0)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kelvin_Yan/article/details/82460137

源:https://www.qtcentre.org/threads/22633-Why-does-QGraphicsItem-scenePos()-return-(0-0)

问题来源:在QGraphicsScene中获取某个item的位置,item定义为QGraphicsEllipseItem对象,希望通过item的scenePos方法获得item在scene中的位置,结果总是返回(0,0)

解决:
因为创建QGraphicsEllipseItem时使用了setRect方法来设置item的位置,这样看上去能达到效果,但其实item的位置依旧为(0,0)。
首先要搞清楚,在QT的Graphics中存在三个坐标系:item coordinates、scene coordinates、view coordinates。
QGraphicsItem::pos()获得的是item coordinates,每个item的中心就是item coordinates的原点。
QGraphicsItem::scenePos() 获得的是item coordinates对应的scene coordinates(QGraphicsItem::mapToScene可以实现同样的功能)。
setRect设定的是item的rect的coordinates,而非item coordinates,调用setRect后item coordinates依旧为(0,0)。
需要调用setPos来修改item在scene中的位置。
注意:若item存在parent item,不能使用该方法,setPos设置的是parent item coordinates

void QGraphicsItem::setPos(const QPointF &pos)

Sets the position of the item to pos, which is in parent coordinates. For items with no parent, pos is in scene coordinates.
The position of the item describes its origin (local coordinate (0, 0)) in parent coordinates.

猜你喜欢

转载自blog.csdn.net/Kelvin_Yan/article/details/82460137