Saturday, 11 April 2015

pyqgis - QGIS 3 - Python : QgsVectorLayerJoinInfo issue


I'm trying to use Python to join a table to a vector layer within QGIS (v. 3.2.0)


Here is the script I use :


>>>root = QgsProject.instance().layerTreeRoot()

>>>ids = root.findLayerIds()
>>>target=QgsProject.instance().mapLayer(ids[1])
>>>print ("target :",target.id())
target : du_fl_pts_e154c28b_4812_41a2_9a78_bf95b7a97926
>>>layerToJoin=QgsProject.instance().mapLayer(ids[0])
>>>print("Layer to join :",layerToJoin.id())
Layer to join : TAXREF_9ab461d0_81d1_4095_b1d0_dce90b20600e
>>>lien = QgsVectorLayerJoinInfo()
>>>lien.targetFieldName = 'CD_REF'
>>>lien.joinLayerId = ids[0]

>>>lien.joinFieldName = 'CD_NOM'
>>>target.addJoin(lien)
True

But after the execution of this script, I have no join on my target layer.


Interesting fact : when I test the same script on the same layers/tables on QGIS 2.18.21 (just changing QgsProject -> QgsMapLayerRegistry and QgsVectorLayerJoinInfo -> QgsVectorJoinInfo) the join works.


Any idea why this doesn't work on QGIS 3?



Answer



You need to rename some of your functions as described in the API for the new QgsVectorLayerJoinInfo class in QGIS 3.


E.g.




  • targetFieldName() should now be setTargetFieldName()

  • joinLayerId() should now be setJoinLayerId()


etc.




So try using something like the following:


lien = QgsVectorLayerJoinInfo()
lien.setJoinFieldName('CD_NOM')
lien.setTargetFieldName('CD_REF')

lien.setJoinLayerId(layerToJoin.id())
lien.setUsingMemoryCache(True)
lien.setJoinLayer(layerToJoin)
target.addJoin(lien)

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