Qt 获取QGraphicsItem在屏幕上的位置,在QGraphicsItem中获取全局位置,转换为screenPos

首先了解几个QGraphicsItem的函数

1 QGraphicsScene* QGraphicsItem::scene() 返回item所在的场景Scene
2 QPointF QGraphicsItem::scenePos() 返回item在场景中的位置

QGraphicsScene的函数

QList<QGraphicsVeiw*> QGraphicsScene::views() 返回Scene所在的view的列表

QGraphicsView的函数

QPointF QGraphicsView::mapToScene(const QPoint &point) const 输入Scene的位置返回全局位置

获得item所在的view,且这个view是活动的

1 QGraphicsView * view; 
2 foreach(view,this->scene() -> views())
3 {
4      if(view-> underMouse()|| view-> hasFocus()) break;
5 } 
6 //如果只有一个view也可以偷懒,如下
7 QGraphicsView* view = this->scene()->views.at(0);

转换为全局位置

1 //获得item在scene中的逻辑位置
2 QPointF scene_pos = this->scenePos();
3 //或者找到item的中心点在scene中位置
4 QPointF scene_pos = this->scenePos() + boundingReact().center();
5 //转换为view中的位置
6 QPointF view_pos = view->mapFromScene(scene_pos);
7 //转换为屏幕上的位置
8 QPoint screen_pos = view->mapToGlobal(view_pos);

这样如果item不通过鼠标右键,而通过某个按键调用右键菜单就可以这样,这样右键菜单的位置就可以正确显示了

1 auto event = new QGraphicsSceneContextEvent();
2 event->setScreenPos(screen_pos);
3 this->contextEvent(event);

QPoint QPointF可能有标错的,见谅

原文地址:https://www.cnblogs.com/ybqjymy/p/14931285.html