3

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?

3

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)
  • 1
    Outstanding, @Joseph! Thank you for your informative response. – Rudy Stricklan Mar 17 '17 at 17:52
  • @RudyStricklan - Most welcome, glad it was helpful :) – Joseph Mar 20 '17 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.