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)
  • 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. – DIV Mar 1 '17 at 15:20
  • Thanks, @DIVAD. I did add code like that to make sure it is selecting, and it is. – Meghann Mears Mar 1 '17 at 15:39
  • @MeghannMears Have you tried doing this manually? Do you have the same problem? – DIV Mar 1 '17 at 15:48
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.

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.