坐标
绝对坐标
QGraphicsScene中的坐标为绝对坐标,重写mousePressEvent方法,可以通过QGraphicsSceneMouseEvent的scenePos方法获取鼠标点击的场景坐标
class MyGraphicsScene :public QGraphicsScene
{
public:void mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent) override{QPointF p11 = mouseEvent->pos();QPointF p = mouseEvent->scenePos();QGraphicsTextItem *item =(QGraphicsTextItem*)items()[0];QPointF pp = item->mapFromScene(p);QPointF pp1 = item->mapToScene(pp);MyGraphicsView *view = (MyGraphicsView*)views()[0];QPointF pp2 = view->mapFromScene(p);QPointF pp3 = view->mapToScene(pp2.toPoint());}
};
一个场景(QGraphicsScene)可以从不同的视图角度(QGraphicsView)看,因此一个场景可以有多个视图角度,而一个视图角度只能有一个场景
mapFromScene和mapToScene
QGraphicsView和QGraphicsItem中都有mapFromScene和mapToScene方法。
mapFromScene:将场景坐标转换为相对于QGraphicsItem(QGraphicsView)的相对坐标,坐标原点在QGraphicsItem(QGraphicsView)的左上角
mapToScene:将相对坐标转换为场景绝对坐标,坐标原点在QGraphicsScene的左上角
为什么说QGraphicsScene是绝对坐标呢?
QGraphicsView 提供了对场景的缩放和移动功能。视图的大小和显示区域可能会影响你如何理解和处理坐标:
缩放:视图可以缩放,导致坐标系的单位变化。例如,当视图缩放为 2 倍时,视图坐标系中的 1 单位将对应场景坐标系中的 2 单位。
平移:视图的平移只会改变视图的显示位置,但场景中的坐标系不会受到影响。
事件
事件传递路径:QGraphicsView -> QGraphicsScene -> QGraphicsItem
某个类如果重写了拦截了某个事件则不会继续向下传递,想要继续向下传递必须调一下QGraphicsView事件。