I have a polygon layer with bounding boxes (boundingLayer). This layer has attribute columns "HEIGHT" and "WIDTH". I want to delete all bounding boxes which have HEIGHT and WIDTH less than 200m. How should I proceed?

boundingLayer = QgsVectorLayer("/home/usr/Desktop/BoundingBoxes.shp", "BoundingBoxes", "ogr")
provider = boundingLayer.dataProvider()
updateMap = {}
# To find the right id of the fields I need:
idHeight = provider.fields().indexFromName( 'HEIGHT' )
idWidth = provider.fields().indexFromName( 'WIDTH' )
iter = provider.getFeatures()
for feature in iter:
    Height = feature.attributes()[idHeight]
    Width = feature.attributes()[idWidth]
    if Height < 200: 
  • Is the relationship between the polygon layer and boundingLayer only spatial, or is there an attribute (e.g. ID) shared by both layers?
    – ArMoraer
    Feb 19, 2016 at 13:24
  • I am sorry, I was probably not clear. I have a shape file containing bounding boxes created using processing.runalg('qgis:polygonfromlayerextent' ...) In the current script I am only working on the shape file with the bounding boxes, the layer with the polygons is not relevant anymore. The idea is for me to delete all bounding boxes with height and width less than 200 m so that I can later clip my polygon layer.
    – ELD
    Feb 19, 2016 at 13:27
  • Ok, added an answer then.
    – ArMoraer
    Feb 19, 2016 at 13:46
  • simply look at Delete Features in Using Vector Layers
    – gene
    Feb 19, 2016 at 15:20

2 Answers 2


Just to provide an alternative to @ArMoraer's great answer, you could also use the following:

boundingLayer = QgsVectorLayer("/home/usr/Desktop/BoundingBoxes.shp", "BoundingBoxes", "ogr")
with edit(boundingLayer):
    request = QgsFeatureRequest().setFilterExpression(u'"HEIGHT" < 200 AND "WIDTH" < 200')
    ids = [f.id() for f in layer.getFeatures(request)]
    for fid in ids:
        layer.deleteFeature( fid )

If you just want to delete a feature (bounding box), that's easy:

for feature in iter:
    height = feature['HEIGHT']
    width = feature['WIDTH']    
    if (height < 200) and (width < 200):
        provider.deleteFeatures( [feature.id()] )

Don't forget to call commitChanges() when you're done with all the deleting:


Your Answer

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

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