I am trying to join a shp and dbf file using the PyQGIS API. The code I'll use is below:
from PyQt4.QtCore import *
vector1 = QgsVectorLayer("path to dbf file", "test1", "ogr")
id1 = vector1.id()
print id1
vector2 = QgsVectorLayer("path to shapefile", "test2", "ogr")
id2 = vector2.id()
print id2
QgsMapLayerRegistry.instance().addMapLayer(vector1)
QgsMapLayerRegistry.instance().addMapLayer(vector2)
info = QgsVectorJoinInfo()
info.joinFieldIndex = QgsMapLayerRegistry.instance().mapLayer(id1).fieldNameIndex("Id1Column0") # Returns 0 as expected
info.joinFieldName = QString(u"Id1Column0")
info.joinLayerId = QgsMapLayerRegistry.instance().mapLayer(id1).id()
info.targetFieldIndex = QgsMapLayerRegistry.instance().mapLayer(id2).fieldNameIndex("Id2Column0") # Returns 0 as expected
info.targetFieldName = QString(u"Id2Column0")
info.memoryCache = True
print info.joinFieldIndex #All the following show the correct values
print info.joinFieldName
print info.joinLayerId
print info.targetFieldIndex
print info.targetFieldName
print info.memoryCache
QgsMapLayerRegistry.instance().mapLayer(id2).addJoin(info)
Querying for the respective field names using QgsVectorLayer.attributeDisplayName(0) yields the respective column names as expected.
Yet when I look in the GUI properties, while the join layer is set correctly, the join field is something different and the target field is empty.
Could anyone shed some light on what goes wrong?
QgsMapLayerRegistry.instance()when you already have the layer there?vector2andvector1– Nathan W Jul 27 '13 at 05:39