Monday, 12 September 2016

qgis - Join table field with shapefile programatically (via PyQgis)?


The following is currently unsuccessful at fulfilling a table field join to a point shapefile in Qgis.
All instances of the join object will print the proper values, and no error is flagged when processing - but the target layer does not exhibit any effect.


Something missing?


    Heads = QgsVectorLayer(headCSV, 'Heads', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(Heads)
self.iface.legendInterface().setLayerVisible(Heads,False)

grid = ftools_utils.getMapLayerByName(unicode('Grid'))
joinObject = QgsVectorJoinInfo()
joinObject.targetFieldName = str('ID')
joinObject.joinLayerID = Heads.id()
joinObject.joinFieldName = str('cellID')
grid.addJoin(joinObject)
grid.reload()

UPDATE:


The following returns 'None'. I expect this is actually supposed to return the field names to be joined? (e.g. - a clue to the mistake)



    print joinObject.joinFieldNamesSubset()

FURTHER UPDATE:


Added the following, and now the previous update command returns the accurate fields to be joined - yet the destination layer does not show 'joined' fields...


    joinObject.setJoinFieldNamesSubset(['someFieldName'])

Answer



This has worked for me:


# Get input (csv) and target (Shapefile) layers
shp=iface.activeLayer()
csv=iface.mapCanvas().layers()[0]


# Set properties for the join
shpField='code'
csvField='codigo'
joinObject = QgsVectorJoinInfo()
joinObject.joinLayerId = csv.id()
joinObject.joinFieldName = csvField
joinObject.targetFieldName = shpField
shp.addJoin(joinObject)


The error you are facing is, believe it or not, by a typo in joinLayerId. The question is, why QGIS doesn't throw an error there?


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...