'How to lock all toolbars via menu in Qt?

I am experimenting with Qt Creator and the Application Example.

I would like to add a checkable menu entry to a toolbar menu that reads "Lock toolbars" and, when checked, locks the positions of all tool bars. I guess that it is a quite common feature.

I have managed to find a command that locks single bars via :

toolBar->setMovable(false);

But I cannot figure out how to lock all toolbars.

Edit

This question used to contain an inquiry concerning the toolbar context menu rather than the standard menu. Since I got an answer concerning the context menu elsewhere I removed it from this question.

How to add an entry to toolbar context menu in qt?



Solution 1:[1]

If you have a pointer to your mainwindow, you can simply find all the toolbars and iterate over them:

// in slot
for (auto *t: mainWindow->findChildren<QToolBar*>())
    t->setMovable(false);

Alternatively, you might want to connect all toolbars to a single toggle action, when you initialise the UI:

// in constructor
for (auto *t: this->findChildren<QToolBar*>())
    connect(action, &QAction::toggled, t, &QToolBar::setMovable);

Solution 2:[2]

One common example with flexible lock options

# Created by [email protected] at 2022/2/15 22:56
import typing

from PySide2 import QtWidgets, QtGui, QtCore


class Window(QtWidgets.QMainWindow):
    def createPopupMenu(self) -> QtWidgets.QMenu:
        menu = super().createPopupMenu()
        menu.addSeparator()
        toolBars: typing.Sequence[QtWidgets.QToolBar] = self.findChildren(QtWidgets.QToolBar)
        for toolbar in toolBars:
            if toolbar.rect().contains(toolbar.mapFromGlobal(QtGui.QCursor.pos())):
                title = "%s %s" % ("Lock" if toolbar.isMovable() else "Unlock", toolbar.windowTitle())
                menu.addAction(title, lambda toolbar=toolbar: toolbar.setMovable(not toolbar.isMovable()))
        menu.addSeparator()
        if any(x.isMovable() for x in toolBars):
            menu.addAction("Lock All", lambda: list(x.setMovable(False) for x in toolBars))
        if any(not x.isMovable() for x in toolBars):
            menu.addAction("Unlock All", lambda: list(x.setMovable(True) for x in toolBars))
        return menu


app = QtWidgets.QApplication()
window = Window()
window.setWindowTitle("Toolbar Example")
for i in range(1, 6):
    toolBar = window.addToolBar(f"ToolBar{i}")
    toolBar.setMovable(i % 2 == 0)
    toolBar.addWidget(QtWidgets.QPushButton(f"ToolBar {i}"))
label = QtWidgets.QLabel("Ready")
label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
window.setCentralWidget(label)
window.resize(800, 600)
window.show()
app.exec_()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toby Speight
Solution 2 BaiJiFeiLong