5

I have a set of layers that need to be joined (Layer Properties > Joins) to one specific layer. The reason for this is that I will be updating and adding new layers into my project and would like a single Action command for the specific layer to automatically have the selected layers join with it. I want to avoid having to run joining/merging algorithms altogether.

Is this easily achievable?

After spending time searching on how to create Actions, most of what I found describe the same command which is how to open up a web browser to search for whatever is in the specified attribute. Unfortunately, the default actions don't seem to contain anything similar to what I am looking for.

5
+50

Combining the answer of this previous question with the QGIS API results in python code that should do what you ask for.

#attach a QgsMapLayerAction to all layers:
joinLayerAction = qgis.gui.QgsMapLayerAction( "Join to layer", iface );
#add the action to the QGIS gui, so that it appears as an action for the layer
qgis.gui.QgsMapLayerActionRegistry.instance().addMapLayerAction(joinLayerAction)

def do_join(layer):
    #layer is a reference to the layer the actions was triggered on

    joinInfo = QgsVectorJoinInfo()
    joinInfo.joinLayerId = 'layer_id'        # TODO: insert correct id here
    joinInfo.joinFieldName = 'primary_key'   # TODO: insert correct key here
    joinInfo.targetFieldName = 'foreign_key' # TODO: insert correct key here
    joinInfo.memoryCache = True              # Tune to your needs

    layer.addJoin(joinInfo)

#connect to action trigger
joinLayerAction.triggeredForLayer.connect(do_join)

Just execute this code in the python console for testing. After that you can implement it as a python plugin or in a project python macro.

  • Many thanks @Matthias, I will test this immediately. – Joseph Aug 12 '14 at 13:24
  • strange...after I insert the id and keys and run the code in the python console, I get this message: execfile(u'C:/Users/Me/Desktop/Test.py'.encode('mbcs')). Any idea as to what it means? – Joseph Aug 12 '14 at 14:19
  • Not really, that is rather a command that you would give to the python console than something the python console should print out. It's hard to explain how this should be related to the code in the answer. – Matthias Kuhn Aug 12 '14 at 15:39
  • Fortunately, this is no longer top priority for my work but it would still be incredibly useful. I will try to find what the problem is on my part and update this question. Thanks again, @Matthias – Joseph Aug 18 '14 at 10:11

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.