Take the 2-minute tour ×

I'm trying to create a popup menu, where I can detect the mouse button that was pressed for a given item. I've created a custom QAction already to build my QMenu, but the triggered signal when the menu item is pressed doesn't provide a QMouseEvent for me to query the button pressed.

Also, I'm setting the a status tip for each QAction, which appears in the status bar when I mouse over it, but it stays even after I close the QMenu. Is this normal behavior?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I'm not sure if I understood what do you want; but if you want to show a popup menu on right mouse click, you should at first in header file of your widget (or window class) override function related to mouse event and declare some function that will show your popup menu. So, the header file should contain these declarations:

void Popup(const QPoint& pt);
void mousePressEvent(QMouseEvent *event);

And in cpp file definitions of functions:

void testQt::mousePressEvent(QMouseEvent *event)

         this ->Popup(event ->pos());

void testQt::Popup(const QPoint& pt)
    QPoint global = this ->mapToGlobal(pt);
    QMenu* pPopup = new QMenu(this);

    QAction* pAction1 = new QAction("Item 1", this);
    QAction* pAction2 = new QAction("Item 2", this);
    pPopup ->addAction(pAction1);
    pPopup ->addAction(pAction2);

    QAction* pItem = pPopup ->exec(global);

    if(pItem == pAction1)
    else if(pItem == pAction2)

Now, when you press right mouse button, a popup menu will appear at cursor's position. I hope this helps.

NOTE: If you want to detect which of mouse buttons is pressed when an action is chosen, you should inherit your own class from QMenu. QMenu class contains protected function mousePressEvent(QMouseEvent *event) which should be overriden and you'll be able to detect if left or right mouse button is pressed when an item is chosen in your menu.

share|improve this answer
No, I can get the popup. I want to know which button was pressed to hide the popup, I guess. –  voodoogiant Dec 24 '10 at 22:42
The choosen Action (Item) is defined in in the line: QAction* pItem = pPopup ->exec(global); I edited the code to be clearer. –  Vladimir Dec 24 '10 at 22:55
Maybe I'm still not making myself clear. I have the menu popping up right now by overriding the mousePressEvent and if the event button is a right-click, I popup the menu. Now, let's say I have an action like "Save Image...". I want to know after the user clicks on it and the menu disappears whether they clicked with the left or right button as they would do two different things. –  voodoogiant Dec 25 '10 at 2:49
add comment

Your Answer


