2

I am attempting to perform a table join from a plug-in/outside of the built-in Python console. This is QGIS 3.16.1 and Python 3.7. I want to join two vector point layers, which have all points in exactly the same places. This is my code for the join:

# Create layers for output files
vectorpoint_filled_one = QgsVectorLayer(outputfile, '', 'ogr')
vectorpoint_filled_two = QgsVectorLayer(outputfile_two, 'final', 'ogr')

# Join tables
join_info = QgsVectorLayerJoinInfo()
join_info.setJoinLayer(vectorpoint_filled_one)
join_info.setJoinFieldName('field1')
join_info.setTargetFieldName('field1')
join_info.setUsingMemoryCache(True)
join_info.setJoinFieldNamesBlockList(['geom_X', 'geom_Y'])
vectorpoint_filled_two.addJoin(join_info)

# add to map canvas
QgsProject.instance().addMapLayer(vectorpoint_filled_two) #loads version from before table join

For some reason, the loaded map is vectorpoint_filled_two before the table join. However, when I also load vectorpoint_filled_one, the vectorpoint_filled_two is loaded (correctly) after the table join:

# Create layers for output files
vectorpoint_filled_one = QgsVectorLayer(outputfile, '', 'ogr')
vectorpoint_filled_two = QgsVectorLayer(outputfile_two, 'final', 'ogr') 

# Join tables - add if statement to skip for no vector layers or no raster layers
join_info = QgsVectorLayerJoinInfo()
join_info.setJoinLayer(vectorpoint_filled_one)
join_info.setJoinFieldName('field1')
join_info.setTargetFieldName('field1')
join_info.setUsingMemoryCache(True)
join_info.setJoinFieldNamesBlockList(['geom_X', 'geom_Y'])
vectorpoint_filled_two.addJoin(join_info)

# add to map canvas
QgsProject.instance().addMapLayer(vectorpoint_filled_one)
QgsProject.instance().addMapLayer(vectorpoint_filled_two) #now loads correctly

This works, but I don't want to load vectorpoint_filled_one, as it is otherwise useless. I have tried various manners of reloading and updating vectorpoint_filled_two after the table join (startEditing() + commitChanges(), reload()), but it keeps loading the older version. I have also tried removing vectorpoint_filled_one after vectorpoint_filled_two is added to the map, but this will also result in the join missing from the loaded layer. Since the second version does work and addJoin returns True, I know the table join and previous code creating the layers are correct.

How do I load the correct version of vectorpoint_filled_two without also loading the other layer?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.