I have a parcels shapefile that contains polygons. Condos are also drawn, but inside the master lot. I want to be able to grab all the condos inside the master lot. I saw this question/answer: Finding all polygons inside of a polygon, but that is for POSTGIS and I'm working with shapefiles. I'm writing a plugin for owners lists, so I need this type of search to be included in order to get a complete owners list. The spatial query doesn't allow a search on the same layer which is a problem.

The basic question is: How do I select polygons inside polygons within the same shapefile?


1 Answer 1


You could use a custom script containing the following function which essentially:

  1. Let's you select the master lot (in case you have more than one in your shapefile).
  2. Uses a spatial index to add all features (which intersect the master lot) to a list.
  3. Deselects the master lot.
  4. Selects all features which lie inside the master lot.

You can create a script from:

Processing Toolbox > Scripts > Tools > Create new script

Then use something like the following:

##Polygon_layer=vector polygon

from qgis.core import QgsSpatialIndex

layer = processing.getObject(Polygon_layer)

# Create spatial index
index = QgsSpatialIndex()
# Get master lot
m_lot = layer.selectedFeatures()
for f in m_lot:
    master_lot = f
# Iterate through all features and add to index
for feat in layer.getFeatures():
    # List to find features which intersect master lot 
    id_list = index.intersects(master_lot.geometry().boundingBox())
# Remove master lot from list
# Deselect master lot
# Select features from id_list

Make sure the script is saved in your /.qgis2/processing/scripts/ directory. Before you run the script, select the master lot from your layer.


  1. A simple polygon containing smaller polygons inside.

    Before running script

  1. Now we select the bigger polygon:

    Selecting master lot

  1. Then run the script to see the selected polygons inside:


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.