Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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?

share|improve this question
    
I am aware of this github.com/qgis/Quantum-GIS/blob/master/python/plugins/sextante/… but I'd prefer to make as much use of the QGIS API as possible. –  Thomas Jul 25 '13 at 23:17
    
Why are you digging into QgsMapLayerRegistry.instance() when you already have the layer there? vector2 and vector1 –  Nathan W Jul 27 '13 at 5:39
    
Mostly because the code is copy and pasted from various parts of the program. It's the minimum example which exhibits the problem and the problem also persists when I'd use vector1 and vector2 instead of the Map Layer Registry –  Thomas Jul 27 '13 at 16:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.