Friday, 24 March 2017

python - QGIS 2.2 - possible to do a JOINS from the Action list?


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.



Answer




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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...