[GIS] QGIS: add a widget to a toolbar other than the Plugins toolbar

pyqgisqgisqgis-custom-widgetstoolbar

I have a QToolButton that I want to add to an existing toolbar. Using the Python Console in QGIS 2.14.12 to debug, here's the code fragment that I'm having a problems with:

iface.toolButton=QToolButton()
iface.toolButton.setIcon(QIcon("C:/Users/Rudy/.qgis2/python/plugins/sandbox/icons/action1.png"))
iface.addToolBarWidget(iface.toolButton)

The toolButton displays in the Plugins toolbar, just like the documentation for addToolBarWidget says :-). However, I want it to display in another existing toolbar, not the Plugins toolbar. There is the addUserInputWidget call, but all that happens when I use that call is that a user input box flashes momentarily on the screen, then disappears. The result is that the toolButton doesn't show up anywhere. Isn't there an API call that would place widgets in any toolbar that I specify?

Best Answer

From the QgisInterface class, most toolbars have a addToolBarWidget method which allows you to directly add your widgets to the relevant toolbar. For example, if you want to add your button to the Raster Toolbar, you could use:

from PyQt4.QtGui import QToolButton, QIcon

iface.toolButton = QToolButton()
iface.toolButton.setIcon(QIcon("C:/Users/Rudy/.qgis2/python/plugins/sandbox/icons/action1.png"))
iface.addRasterToolBarWidget(iface.toolButton)

However, not all toolbars are listed such as the LabelToolbar. In this case, we will need to iterate through the names of all available toolbars, find the label toolbar and add your widget:

from PyQt4.QtGui import QToolButton, QIcon, QToolBar

iface.toolButton = QToolButton()
iface.toolButton.setIcon(QIcon("C:/Users/Rudy/.qgis2/python/plugins/sandbox/icons/action1.png"))

# Find all ToolBars
for x in iface.mainWindow().findChildren(QToolBar): 
    # print x.windowTitle()
    if x.windowTitle() == 'Label Toolbar':
        x.addWidget(iface.toolButton)