I need to prevent that selecting a context menu action fire a mouse press event underneath
-
On right button pressed i create a context menu this way:
QMenu menu(this); QMenu *modeMenu = new QMenu(tr("Mode"), this); menu.addMenu(modeMenu); { QAction * mixModeAction = new QAction(tr("Mix"), this); modeMenu->addAction(mixModeAction); connect(mixModeAction, &QAction::triggered, [&](bool) { qDebug() << "menu mix"; mode = Mix; //... rebuild widgets ... }); / /... }
In lambda function I rebuild the structure of widgets underneath. The problem is that when the user clicks and triggers the action a mouse press slot on a widget underneath is triggered too, causing the application to break.
Ho can I prevent the mouse press event to trigger when selecting a menu action? -
Hi
where do you have this code ?
Normally your would return true to indicated you do not want event propagation.bool MyWidget::event(QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_Tab) { // special tab handling here return true; } } else if (event->type() == MyCustomEventType) { MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event); // custom event handling here return true; // eat it } return QWidget::event(event); }
Also using setContextMenuPolicy(Qt::CustomContextMenu); and
http://doc.qt.io/qt-5/qwidget.html#customContextMenuRequested
have not such issue. -
Sorry I can' t follow you:
if I set context menu policy in this widget, it doesn't open context menu anyway.
I did it in QTreeWidget in the same application and it worked. Not here...I subclassed a QMdiSubWindow.
In this window there are some boxes containing other widgets and finally in one of them there's a qcustomplot which occupies 80% of the whole subwiindow area.I 've overriden the subwindow ::mousePressEvent(QMouseEvent *event) and here i check if right button is pressed: if so it opens that menu.
when user presses mouse button over a qcustomplot it triggers mousePressEvent(QMouseEvent *event) which reemits mouse press event and that's grabbed by my slot. when user presses mouse button over a different part of subwindow it triggers directly my slot .
when I have my context menu over qcustomplot if I click on a menu entry it correctly fires its lambda but it fires qcustomplot mousePressEvent(QMouseEvent *event) too.
-
Hi
the customContextMenuRequested method works better and you should
implement that instead. (with setContextMenuPolicy(Qt::CustomContextMenu); )
You need to implement the the method also. Not just set flag.
You avoid the event being sent to other widgets and that flag and that method is really how
it was meant to be used :) -
ok thank you. I'll try again. On this widget it didn't work the first time thou I simply copied the same code I used on a QTreeWidget I subclassed and in that class it works.
@Black-Imp
It should work. :)