6

I have a toolbar and I want it to have an already existing action, but checking the documentation I only found methods to add newly created actions, not already existing ones. Is there a way to do this?

The action I want to add is the Touch, Zoom and Pan tool from Map Navigation toolbar. I know I can reference it this way:

qgis.utils.iface.mapNavToolToolBar().actions()[0]

But there's nothing I can do with it.

2 Answers 2

5

You need:

To add a new toolbar with:

toolbar = iface.addToolBar(u'My test')

Then, add the native action to the newly created toolbar:

# Example for pan
toolbar.addAction(iface.actionPan())

If you want the full list of actions, go to the QGisInterface API documentation.

0
5

You might find it useful to look at the code generated by the Plugin Builder plugin, especially the add_action() method it generates, which is what hooks plugin icons into toolbars and menus.

This snippet looks promising...

if add_to_toolbar:
        self.toolbar.addAction(action)

You already found out how to get the existing action (a QAction object). Now you just need the snippet to get the toolbar you want to add the icon to.

Looking at the API for qgisInterface it seems there's already a method to let you create a toolbar...

myaction = qgis.utils.iface.mapNavToolToolBar().actions()[0]
mytoolbar = qgis.utils.iface.addToolBar("helloworld")
mytoolbar.addAction(myaction)

Just tried that in the console and it works. (If it doesn't appear, right click on the toolbar background and make sure 'helloworld' is checked)

EDIT

Just realised you want to glom onto an existing toolbar, which you haven't created yourself.

QgisInterface extends QObject, which has a findChild(type,name) method. However, running this from the console returns an empty list

print qgis.utils.iface.findChildren(PyQt4.QtGui.QToolBar,u'helloworld')
>>> []

Hopefully someone with more Qt knowledge can answer this. I think there may be an issue with reading data like this across threads :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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