Project: QGIS

Version: 3.6.0

Feature: Iterate over parts of a QgsGeometry

This new PyQGIS API allows easy iteration over all the parts of a geometry, regardless of the geometry's type. E.g.

geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
  print(part.asWkt())

geometry = QgsGeometry.fromWkt( 'LineString( 0 0, 10 10 )' )
for part in geometry.parts():
  print(part.asWkt())

There are two iterators available. QgsGeometry.parts() gives a non-const iterator, allowing the parts to be modified in place:

geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
   part.transform(ct)

For a const iteration, calling .const_parts() gives a const iterator, which cannot edit the parts but avoids a potentially expensive QgsGeometry detach and clone

geometry = QgsGeometry.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.const_parts():
   print(part.x())

This feature was funded by North Road

This feature was developed by Nyall Dawson (North Road)