【发布时间】:2012-04-09 22:25:28
【问题描述】:
用例: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
The doc says:
如果你想知道一个项目在视口中的位置,你可以在项目上调用 QGraphicsItem::mapToScene(),然后在视图上调用 QGraphicsView::mapFromScene()。
这正是我正在做的,对吧?
偶然发现a thread in a german forum 暗示:
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);
使用它可能会更概括地回答我的问题...
【问题讨论】:
-
我正要发布回复,但重新阅读文档后我认为我同意您的分析:QGraphicsView::mapFromScene 应该提供视口坐标(值得检查)。唯一的问题是,mapToGlobal 中 MDI 子组件中的小部件上是否存在潜在错误。
-
@JamesTurner 那么你的第一个猜测是什么(你会写下来作为回应)?
标签: c++ qt position viewport qgraphicsitem