2

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"?

Taras
35.8k5 gold badges77 silver badges151 bronze badges
asked Feb 23, 2020 at 21:45

2 Answers 2

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.

Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Feb 24, 2020 at 17:16
0
2

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)

enter image description here

Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Feb 24, 2020 at 4:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.