3

I am trying to join layers programmatically following the answers in the Joining table field with shapefile using PyQGIS

# 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()

...

But I get an error about QgsVectorJoinInfo not being defined. I tried to import it with:

from qgis.core import QgsVectorJoinInfo

(because the documentation linked above says that QgsVectorJoinInfo is in the core library).

How should I import it properly or otherwise make the above code work? (In general, how to tell from the documentation which library to import?)

Taras
  • 32,823
  • 4
  • 66
  • 137
tinlyx
  • 11,057
  • 18
  • 71
  • 119

1 Answers1

11

The class has been renamed from QgsVectorJoinInfo to QgsVectorLayerJoinInfo.

You now need to call each join function with their associated parameter:

...
csvField = 'id'
shpField = 'ID'
joinObject = QgsVectorLayerJoinInfo()
joinObject.setJoinFieldName(csvField)
joinObject.setTargetFieldName(shpField)
joinObject.setJoinLayerId(csv.id())
joinObject.setUsingMemoryCache(True)
joinObject.setJoinLayer(csv)
shp.addJoin(joinObject)

Example:

Example

Taras
  • 32,823
  • 4
  • 66
  • 137
Joseph
  • 75,746
  • 7
  • 171
  • 282