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?
Inherit QToolbar and reimplement contextMenuEvent()
.
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.
contextMenuPolicy
of the toolbar to NoContextMenu
, the context menu still appears. BUT if you set it to CustomContextMenu
and don't implement a custom context menu function, no context menu appears... strange. –
Hornet 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.
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.
QToolbar
children in createPopupMenu
. Looking in direct children of the QMainWindow
only seems to work. –
Lusk Inherit QToolbar and reimplement contextMenuEvent()
.
The simplest thing to do is:
self.toolbar.toggleViewAction().setVisible(False)
Unlike self.toolbar.toggleViewAction().setEnabled(False)
, which still shows the disabled popup if you're right-clicking the toolbar for any reason.
© 2022 - 2024 — McMap. All rights reserved.