I am writing a PyQGIS Plugin in which I need to do an overlay.
The code of the function doing the overlay look like:
measure = self.dlg.fcbMeasure.layer()
area = self.dlg.fcbArea.layer()
params = {'INPUT':measure,
'OVERLAY':area,
'OUTPUT':"memory:land_water",
'INTERSECTION':"memory:land_water"}
processing.runAndLoadResults("qgis:intersection", params)
I thought either OUTPUT
or INTERSECTION
should name the output layer, but the layer that is created is just called Intersection - how can I run the intersection and end up with a memory layer named "land_water"
?
2 Answers 2
Looking a bit more around, I found that processing returns a directory with (at least) a key 'OUTPUT'
. The value corresponding to this key is a unique layer id.
So I can do:
output = processing.runAndLoadResults("qgis:intersection", params)
newlayer = QgsProject.instance().mapLayer(output['OUTPUT'])
newlayer.setName('land_water')
Then I know I have the layer I just created, which is something that is not guaranteed if I start using mapLayersByName()
as there may be more map layers with the same name in the project.
Perhaps someone will know a better way, but the only way I know is via the following workaround:
measure = self.dlg.fcbMeasure.layer()
area = self.dlg.fcbArea.layer()
params = {'INPUT': measure,
'OVERLAY': area,
'OUTPUT': 'memory'}
processing.runAndLoadResults('qgis:intersection', params)
result = QgsProject().instance().mapLayersByName('Intersection')[0]
result.setName('land_water')
E.g. create a reference to the newly created layer and simply change it's name using the setName()
method.
The following also works providing you have the option in processing settings to 'Use filename as layer name' checked (see image below).
measure = self.dlg.fcbMeasure.layer()
area = self.dlg.fcbArea.layer()
params = {'INPUT': measure,
'OVERLAY': area,
'OUTPUT': 'land_water'}
processing.runAndLoadResults('qgis:intersection', params)
Explore related questions
See similar questions with these tags.