View Full Version : Context menu for QAction

28th September 2009, 15:29
I have a main window with a toolbar which I've added some QActions to.
QToolBar::addAction lets me specify a slot to be called when the action is triggered, i.e. clicked on with the left mouse button.

How can I have a slot called when right-clicking the QAction (for e.g. a context menu)?

28th September 2009, 18:10
If right-clicking is not a strict requirement for you, you can manually add a QToolButton to the toolbar and set a menu with QToolButton::setMenu(). You can find an image of the resulting button at the very bottom of this page:


29th September 2009, 14:51
It seems I had confused QMenuBar with QToolBar. Let's start over.

I have a QMainWindow with a QMenuBar on top. There are only a few menus and I'd like to use the remaining space in the menu bar for tool buttons. QMenuBar does not have an addWidget(), and its layout() returns NULL so I can insert a widget through its layout.
I can insert QActions though, and they can call a slot when clicked.

The tool button I'm having a problem with has an obvious action associated with it that I want to activate by clicking - no problem. But it also has some oddball-functions that I'd like to access through a menu by right-clicking it (or possibly through the little arrow that QToolButton has).
I've tried:

1) Creating a QAction whose triggered() signal activates the main function and the rest through setMenu() on the QAction prior to inserting it into the QMenuBar. This fails - left click opens the menu and right click does nothing.

2) Inserting a QAction into the QMenuBar that really is a QWidgetAction whose createWidget() returns a QToolButton or some other custom widget where I reimplement mousePressEvent() to handle both mouse buttons. Fails because createWidget() is never called when the QWidgetAction is inserted into the QMenuBar.

Is it true then that QMenuBar cannot take a QWidget and that it also insists on consuming the entire width of the QMainWindow even if it has only a small number of menus? (otherwise it might be possible to put a QToolBar to the right of the QMenuBar)

29th September 2009, 15:31
Im not sure but that would be consistent with every Gui I saw the last 15 years.

29th September 2009, 19:01
Well, I have Google's search field immediately to the right of the menubar in Firefox as I type this.

The solution that seems promising now is to not let the QMainWindow have a menubar, but rather let the central widget of the QMainWindow have a QMenuBar at the top with a QToolbar next to it.