2

I'm learning to use the python console within QGIS.

I want to add layers like iface.actionAddOgrLayer(), open projects and more by the action-function, but without any response - only the string comes up in the console like "object at 0X....."

Functions like zoom works. Did I miss something here in the API-documentation?

3

Actions are meant to be tied to buttons and menu items that are then activated by events. The function of the action happens when the button is clicked.

To simulate this, you need to call the activate method on an action and pass it an event. I'm not sure how important the event is, but it works for me if I construct one.

from PyQt4.QtGui import QAction
iface.actionAddOgrLayer().activate(QAction.ActionEvent())

You should probably use the methods described in the following link to add layers anyway, since it lets you handle errors and so on:

http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html

But if you really want to activate the same action as the menu without having to trigger an action event, you can use a method on the main Qgis window:

mw = iface.mainWindow()
mw.addVectorLayer()

That will open a dialog box and prompt the user for some layer, and add it to the layer list and put it on the canvas. Just like you used the menu item.

I suspect most of the actions on the menu items translate through to similar methods on the main Qgis window object. Check the API calls for QgisApp for many more.

  • That's a little embarrassing, why didn't I see that. :-) I've been around the actions before. Thanks. – CARTOS Jan 2 '16 at 14:25
  • activating actions might not be the right thing though, see edits, or see the source code to see what functions are eventually called when actions are activated. – Spacedman Jan 2 '16 at 14:26

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.