Question

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?

Was it helpful?

Solution

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)
{
     if (event->button() == Qt::RightButton) {

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

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.

OTHER TIPS

I know this is a very old post. But if you want to know what button you have clicked in a popup menu/ context menu. Lets say you press button Save, that's connected with signals and slots etc. In the slot call a method called sender();. This returns a QObject which you can cast into your QAction* and get the data etc from it .

void MyClass::showMenu()
{
     auto action(new QAction*("Blah", ui->my_toolbar));

     QObject::connect(action, &QAction::triggered, this, &MyClass::mySlot);
}

void MyClass::mySlot()
{
     auto myAction(static_cast<QAction*>(sender()));
     myAction->doAwesomeStuff();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top