4

I have a feature layer and a buffer of that feature layer and am trying to cut out the features from the buffers. This would be trivial, except that the buffers overlay multiple features, so I need to select each feature from the two layers individually, use the difference tool to export them to individual layers, and finally merge them all at the end.

I've written a Python script to automate the selection/difference tool part of this but it seems to be using all features from the layers, and not only the selected ones. I have tested that the code for the selection is working so I believe it is the call of the difference tool that is not working as expected. I understood from the documentation that it should only use the selected features, but perhaps either my understanding or my code is wrong.

I am using QGIS 2.18.3.

import processing
buffer_layer = QgsVectorLayer("buffer.shp", "buffer_layer", "ogr")
patch_layer = QgsVectorLayer("patches.shp", "patch_layer", "ogr")
for feature in buffer_layer.getFeatures():
 buffer_layer.setSelectedFeatures([feature.id()]) 
 site_name = feature.attributes()[0]
 patch_list = []
 for patch in patch_layer.getFeatures():
 if patch.attributes()[1] == site_name:
 patch_list.append(patch.id())
 patch_layer.setSelectedFeatures(patch_list)
processing.runalg("qgis:difference",buffer_layer,patch_layer,0,"output_%s.shp" % site_name)
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Mar 1, 2017 at 15:03
3
  • Make sure again that your script selects features, cuz it looks like it doesn't. Add to your code some prints, like buffer_layer.selectedFeatures() and patch_layer.selectedFeatures() to be sure. Commented Mar 1, 2017 at 15:20
  • Thanks, @DIVAD. I did add code like that to make sure it is selecting, and it is. Commented Mar 1, 2017 at 15:39
  • @MeghannMears Have you tried doing this manually? Do you have the same problem? Commented Mar 1, 2017 at 15:48

1 Answer 1

5

You will need to load the layers in QGIS for processing algorithms to work on selected features.

Try replacing -

buffer_layer = QgsVectorLayer("buffer.shp", "buffer_layer", "ogr")
patch_layer = QgsVectorLayer("patches.shp", "patch_layer", "ogr")

with -

buffer_layer = iface.addVectorLayer("buffer.shp", "buffer_layer", "ogr")
patch_layer = iface.addVectorLayer("patches.shp", "patch_layer", "ogr")

in your code.

answered Mar 1, 2017 at 17:07
0

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.