0

I'm using a custom QGraphicsWidget and when I right click on it I want to bring up a menu. I'm starting it like this:

void myQGraphicsWidget::mousePressEvent(QGraphicsSceneMouseEvent *event){
    if(event->button() & Qt::RightButton){
        const QString test = "test";
        QMenu  menu;
        menu.setTitle(test);
        menu.addAction(test);
        menu.exec(mapToScene(event->pos()).toPoint());
        //menu.exec(mapToScene(QPointF(0,0)).toPoint());
    }
}

but the menu shows up way outside of the main application window towards the bottom right of my other monitor. When I use the commented out version then it appears resting on top of my main window. I've tried adjusting the point manually to massage it inside the window but it will just jump to either resting on top of the window or hanging from the bottom, never inside.

1 Answers1

0

QMenu::exec takes a global position; you're taking the widget-relative position and mapping it to the scene position.

Try this instead:

    menu.exec(event->screenPos());
Taylor Brandstetter
  • 3,523
  • 15
  • 24
  • What type of event has a globalPos() member function? I was able to get my QMenu to finally be displayed inside the main window, but it is a bit off. I'm calling it like this menu.exec(event->widget()->mapToGlobal(event->pos().toPoint())); I could just manually toss in some offsets to make it appear close, but I'd like to know if there is a better way to do this now. – RidesTheShortBus Nov 19 '13 at 18:38
  • @RidesTheShortBus Oh, I didn't notice that it was a `QGraphicsSceneMouseEvent`. But I think `screenPos()` is equivalent. Edited my answer. – Taylor Brandstetter Nov 19 '13 at 18:41
  • QContextMenuEvent has a globalPos() member. In my experience, QMenu.exec() will not open a menu outside the app's windows. For a QContextMenuEvent from a user pressing the ContextMenuKey , when the pointer is outside the app's windows, the event's pos() is (0,0), disagreeing with globalPos(). Possibly human interface guidelines say that you should not open a menu outside your app's windows, and Qt is enforcing that? This is related, but not the same as your problem. – bootchk Mar 06 '14 at 10:48
  • 1
    My mistake: (0,0) does agree with globalPos(), but it is not the accurate position of the mouse. Also, you can open a menu outside your windows, for example at QCursor.pos(), the current position of the mouse, instead of the inaccurate position of the mouse at the time the event was created. It might not make much user interface sense to open a menu outside your windows. – bootchk Mar 06 '14 at 12:14