PDA

View Full Version : How to disable context menu of a toolbar in QMainApplication



mtrpoland
25th June 2007, 18:54
I have a small application that inherits QMainWindow. I have implemented my own mechanism enabling user to show and hide Toolbars. It is placed in QMenuBar and contains a few checkable actions. The problem is that when one clicks a right button on a free space on a ToolBar he gets the context menu that enables him to show and hide toolbars. Thus when one switches one toolbar off in this context menu, the checkable action i menubar remains checked as it is not related to the context menu. I tried to reimplement QMouseEvent and simply do nothing inside just to remove the feature of ToolBar context menu but it didn't work. So here comes my question:

How to disable context menu that emerges when we click right mouse button on a QToolBar that is a part of QMainApplication class?

MJ

marcel
25th June 2007, 19:01
You tried with the wrong event.
The event is called QContextMenuEvent.

The best choice is to install the main window as event filter for all the toolbars and simply catch the context menu event( don't let it reach the toolbar(s)).

If you have problems implementing/understanding this, you can ask here.

Regards

mtrpoland
25th June 2007, 21:20
Something like this?

MWin inherits QMainWindow



bool MWin::eventFilter(QObject* object, QEvent* event) {
if(event->type() == QEvent::ContextMenu) {
QContextMenuEvent* mevent = static_cast<QContextMenuEvent *>(event);
if(mevent->reason() == QContextMenuEvent::Mouse) {
qDebug("I have blocked the context menu.");
return true;
} else return QObject::eventFilter(object, event);
}
else return QObject::eventFilter(object, event);
}


and installation:



...
fileToolBar->installEventFilter(this);
...
modeToolBar->installEventFilter(this);
...
actionToolBar->installEventFilter(this);
...

marcel
25th June 2007, 21:25
More like this. You must test for the objects you're installing the filter for.


bool MWin::eventFilter(QObject* object, QEvent* event) {
if(event->type() == QEvent::ContextMenu &&
( object == fileToolbar || object == modeToolBar ... ) ) {
QContextMenuEvent* mevent = static_cast<QContextMenuEvent *>(event);
if(mevent->reason() == QContextMenuEvent::Mouse) {
qDebug("I have blocked the context menu.");
return true;
} else
return false;
}
else
return QObject::eventFilter(object, event);
}



Regards

jpn
25th June 2007, 21:40
The preferred way would be to use QToolBar::toggleViewAction() in the menu bar. If you want to create a custom context menu, reimplement QMainWindow::createPopupMenu(). If you want to disable the context menu, you can set the context menu policy (http://doc.trolltech.com/4.3/qwidget.html#contextMenuPolicy-prop) of the main window to Qt::NoContextMenu.