Wednesday, 8 March 2017

How to select multi-part polygons from a layer using PyQGIS


My script is -


# Find all multipart features in the active layer
l = iface.activeLayer()

iter = l.getFeatures()
geoms = []
for feature in iter:
    geom = feature.geometry()
    if geom.isMultipart():
        l.select(feature.id())
        geoms.append(geom)

print 'There are %i multipart features in this layer' % len(geoms)


I don't know the exact problem with this script. Using this script in the Python console should select all multi part features in the active layer but in my case no multi section polygons fetched, while I can easily see multi section polygons exists in my polygon file.



Answer



This is an easier alternative.


layer = iface.activeLayer()   
expr = QgsExpression( "num_geometries( $geometry ) > 1" )
it = layer.getFeatures( QgsFeatureRequest( expr ) )
ids = [i.id() for i in it]

Now you can know how many features are multi-part:


print 'There are {} multipart features in this layer'.format(len(ids))


And even select multi-part features:


layer.setSelectedFeatures( ids )

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...