2

I'm using QGIS 3.4.3 and I have created some actions for vector layers. I did it interactively and this part is working.

enter image description here

Now I wanted to know if there is a mechanism how I could create my actions directly in Python. I don't want to create these actions interactively in QGIS no more.


I figured out I can handle it with QgsAction. It works for me.

    def my_test(self):
    aLayer = self.iface.activeLayer()

    file1 = self.plugin_dir + "/action1.txt"  
    fw = open(file1, 'r')
    txt = fw.read()
    fw.close()

    action = QgsAction (QgsAction.GenericPython, 'test', txt)
    my_scopes = {'Field'}

    actionManager = aLayer.actions()
    i=0
    for a in actionManager.actions():
     if a.name() == action.name():
      i=1
      break;
    if i == 0:        
     action.setActionScopes(my_scopes)
     actionManager.addAction(action)

Now I need to know how I can set flag: "Enable only when editable". The option is disabled per default. I tried to use QgsAction with parameter enabledOnlyWhenEditable=True but it doesn't work. TypeError: 'enabledOnlyWhenEditable' is an unknown keyword argument

2

Use the following code to add an action.

layer = iface.activeLayer()
acManager = layer.actions()

acActor = QgsAction(1 , "Fuu", "print 'Baa'", False) 
acManager.addAction(acActor )

The QgsAction takes the Argument:

  • 1: This is the Action type as described in the QGIS reference to QgsAction
  • "Fuu": How your action will be called. It can be any String
  • "print 'Baa'": The Function body with """ you can use multiline statements
  • False: capture. If this is set to true, the output will be captured when an action is run

Tested with QGIS 2.18. DISCLAIMER: Posted before the update of the question

  • Thank you for your help. The code works also for QGIS 3.4.3. Do you know how I can set flag enabledOnlyWhenEditable to True? It looks for me like enabledOnlyWhenEditable can not be set in constructor. – DG85 Jan 14 at 14:54
  • You can use the isEditable method of the vector layer e.g: iface.activeLayer().isEditable() – Zoltan Jan 14 at 20:16

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.