使用场景:这应该是一个相当常见的问题。在一个带有QMdiArea的普通QMainWindow中,存在一个带有QGraphicsView的mdiChild。此视图显示一个带有QGraphicsItems的QGraphicsScene。对这些项之一进行右键单击将选择(关注)该项并打开上下文菜单,方便地放置在屏幕坐标QGraphicsSceneMouseEvent::screenPos()
处。这正在按预期工作。
现在我想在用户按下按键(例如Qt :: Key_Menu)时显示相同的上下文菜单。我知道所选(聚焦)的项目,我知道显示场景的视图。
所以我的问题是:
以正确的方式获取场景中QGraphicsItem的可见表示在全局屏幕坐标中的位置是什么?
以下内容无法正常工作:
QGraphicsItem *item = ...; // is the currently selected item next to which the context menu shall be opened
QGraphicsScene *scene = ...; // is the scene that hosts the item
QGraphicsView *graphicsView = ...; // is the view displaying the scene, this inherits from QWidget
// get the position relative to the scene
QPointF sp = item->scenePos();
// or use
QPointF sp = item->mapToScene(item->pos());
// find the global (screen) position of the item
QPoint global = graphicsView->mapToGlobal(graphicsView->mapFromScene(sp));
// now
myContextMenu.exec(global);
// should open the context menu at the top left corner of the QGraphicsItem item, but it goes anywhere
文档中提到:
如果你想知道一个项在视口中的位置,可以在项上调用QGraphicsItem::mapToScene(),然后在视图上调用QGraphicsView::mapFromScene()。
这正是我正在做的事情,对吗?
刚巧发现一个德国论坛的帖子指出:
QGraphicsView *view = item->scene()->views().last();
甚至更好的是:
QGraphicsView *view;
foreach (view, this->scene()->views())
{
if (view->underMouse() || view->hasFocus()) break;
}
// (use case in the forum thread:) // QMenu *menu = new QMenu(view);
使用这个可能会让我的问题得到更一般化的回答...