Question

In Qt, if I right-click on a toolbar the menu will be shown that allows me to hide the toolbar. I need to disable this functionality because I don't want the toolbar to possible to hide. Is there a way to do this?

Was it helpful?

Solution

Inherit QToolbar and reimplement contextMenuEvent().

OTHER TIPS

I was able to set the ContextMenuPolicy directly on the toolbar (not the main window), as long as I used either Qt::PreventContextMenu or Qt::ActionsContextMenu. Prevent eliminated the context menu and made right-click have no effect on the toolbar, while Actions made a nice context menu composed of the actions already in my toolbar. Qt::NoContextMenu didn't seem to have any effect.

toolbar->setContextMenuPolicy(Qt::PreventContextMenu);

Use setContextMenuPolicy (Qt::NoContextMenu) for the main window of the toolbar.

Override QMainWindow::createPopupMenu() e.g.

QMenu* MyApp::createPopupMenu()
{
  QMenu* filteredMenu = QMainWindow::createPopupMenu();
  filteredMenu->removeAction( mUnhidableToolBar->toggleViewAction() );
  return filteredMenu;
}

Note that the other answers that suggest disabling the context menu will only work if you want to disable hiding/showing of all toolbars and all dock widgets.

There are several ways to achieve this without having to alter the contextMenu functionality. See the following 3 PySide examples:

1. Disable the toggleViewAction of the QToolBar:

UnhidableToolBar = QToolBar()
UnhidableToolBar.toggleViewAction().setEnabled(False)

2. Connect to the visibilityChanged signal:

toolbar.visibilityChanged.connect(lambda: toolbar.setVisible(True))

3. Subclass QToolBar and use the hideEvent:

class UnhideableQToolBar(QToolBar):
    def hideEvent(self, event):
        self.setVisibile(True)

Recommendation:

While 2 & 3 are pretty dirty, solution 1 shows the toolbar in the context menu like a QDockWidget that has the feature DockWidgetClosable set. So either use solution 1 or if you want to remove the action have a look at Steven's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top