1

I am writing a pygis 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"?

1

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.

Edit: 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)

enter image description here

0

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.

3
  • In this way, you probably add the output layer to layer list twice. – Kübra Feb 25 '20 at 16:12
  • Nope, it works as expected. I am just fetching a pointer to the layer. – MortenSickel Feb 25 '20 at 18:31
  • I didn't realize that you used mapLayer. I thought it was addMapLayer. – Kübra Feb 26 '20 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.