I want to find the bounding box of several features selected by their attributes. Here's what I've been trying:

tNumList = [8,9,10,11]
selectGeom = QgsGeometry()
for tNum in tNumList:
    request = QgsFeatureRequest().setFilterExpression( u'"Territory" = {}'.format(tNum))
    iter = territoryBorders.getFeatures(request)
    feat = QgsFeature()
    print selectGeom.boundingBox().width()

Is there a better way to get a single feature from a layer then using the getFeatures(request)?

This just gives me empty rectangles. What am I doing wrong?

1 Answer 1


I've optimized and corrected your code.

  1. All features are selected in one request with SQL in
  2. First feature is taken to be combined with something (this was the mistake in your code)
  3. Only the bounding boxes are combined to get result faster

Optimized code:

request = QgsFeatureRequest().setFilterExpression( u'"Territory" in (8, 9, 10, 11)')
iter = territoryBorders.getFeatures(request)
feat = QgsFeature()
box = feat.geometry().boundingBox()
while iter.nextFeature(feat):
  • 1
    +1 on combining the bbox instead of real geometries. Jan 9, 2016 at 12:45

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.