Class: QgsAbstractGeometry

Abstract base class for all geometries.

Note

QgsAbstractGeometry objects are inherently Cartesian/planar geometries. They have no concept of geodesy, and none of the methods or properties exposed from the QgsAbstractGeometry API (or QgsGeometry API) utilize geodesic calculations. Accordingly, properties like length() and area() and spatial operations like centroid() are always calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for working with geodesic calculations and spatial operations on geometries, and should be used whenever calculations which account for the curvature of the Earth (or any other celestial body) are required.

Class Hierarchy

Inheritance diagram of qgis.core.QgsAbstractGeometry

Subclasses

QgsCurve

Abstract base class for curved geometry type.

QgsSurface

Surface geometry type.

QgsGeometryCollection

Geometry collection.

QgsPoint

Point geometry type, with support for z-dimension and m-values.

Abstract Methods

addMValue

Adds a measure to the geometry, initialized to a preset value.

addZValue

Adds a z-dimension to the geometry, initialized to a preset value.

adjacentVertices

Returns the vertices adjacent to a specified vertex within a geometry.

asGml2

Returns a GML2 representation of the geometry.

asGml3

Returns a GML3 representation of the geometry.

asKml

Returns a KML representation of the geometry.

asQPainterPath

Returns the geometry represented as a QPainterPath.

asWkb

Returns a WKB representation of the geometry.

asWkt

Returns a WKT representation of the geometry.

boundary

Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the geometry).

boundingBox3D

Returns the 3D bounding box for the geometry.

clear

Clears the geometry, ie reset it to a null geometry

clone

Clones the geometry by performing a deep copy

closestSegment

Searches for the closest segment of the geometry to a given point.

compareToSameClass

Compares to an other geometry of the same class, and returns a integer for sorting of the two geometries.

coordinateSequence

Retrieves the sequence of geometries, rings and nodes.

createEmptyWithSameType

Creates a new geometry with the same class and same WKB type as the original and transfers ownership.

deleteVertex

Deletes a vertex within the geometry

dimension

Returns the inherent dimension of the geometry.

draw

Draws the geometry using the specified QPainter.

dropMValue

Drops any measure values which exist in the geometry.

dropZValue

Drops any z-dimensions which exist in the geometry.

fromWkb

Sets the geometry from a WKB string.

fromWkt

Sets the geometry from a WKT string.

fuzzyDistanceEqual

Performs fuzzy distance comparison between this geometry and other using an epsilon.

fuzzyEqual

Performs fuzzy comparison between this geometry and other using an epsilon.

geometryType

Returns a unique string representing the geometry type.

insertVertex

Inserts a vertex into the geometry

isValid

Checks validity of the geometry, and returns True if the geometry is valid.

moveVertex

Moves a vertex within the geometry

nextVertex

Returns next vertex id and coordinates

normalize

Reorganizes the geometry into a normalized form (or "canonical" form).

partCount

Returns count of parts contained in the geometry.

removeDuplicateNodes

Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.

ringCount

Returns the number of rings of which this geometry is built.

segmentLength

Returns the length of the segment of the geometry which begins at startVertex.

simplifyByDistance

Simplifies the geometry by applying the Douglas Peucker simplification by distance algorithm.

snappedToGrid

Makes a new geometry with all the points or vertices snapped to the closest point of the grid.

swapXy

Swaps the x and y coordinates from the geometry.

toCurveType

Returns the geometry converted to the more generic curve type.

transform

Transforms the geometry using a coordinate transform

vertexAngle

Returns approximate angle at a vertex.

vertexAt

Returns the point corresponding to a specified vertex id

vertexCount

Returns the number of vertices of which this geometry is built.

vertexNumberFromVertexId

Returns the vertex number corresponding to a vertex id.

wkbSize

Returns the length of the QByteArray returned by asWkb()

Methods

asJson

Returns a GeoJSON representation of the geometry as a string.

is3D

Returns True if the geometry is 3D and contains a z-value.

isMeasure

Returns True if the geometry contains m values.

parts

Returns Java-style iterator for traversal of parts of the geometry.

setZMTypeFromSubGeometry

Updates the geometry type based on whether sub geometries contain z or m values.

simplifiedTypeRef

Returns a reference to the simplest lossless representation of this geometry, e.g. if the geometry is a multipart geometry type with a single member geometry, a reference to that part will be returned.

sortIndex

Returns the sort index for the geometry, used in the compareTo() method to compare geometries of different types.

vertices

Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.

wkbType

Returns the WKB type of the geometry.

wktTypeStr

Returns the WKT type string of the geometry.

Virtual Methods

In PyQGIS, only methods marked as virtual can be safely overridden in a Python subclass of QgsAbstractGeometry. See the FAQ for more details.

area

Returns the planar, 2-dimensional area of the geometry.

boundingBox

Returns the minimal bounding box for the geometry

boundingBoxIntersects

Returns True if the bounding box of this geometry intersects with a rectangle.

calculateBoundingBox

Default calculator for the minimal bounding box for the geometry.

calculateBoundingBox3D

Calculates the minimal 3D bounding box for the geometry.

centroid

Returns the centroid of the geometry

childCount

Returns number of child geometries (for geometries with child geometries) or child points (for geometries without child geometries - i.e. curve / point).

childGeometry

Returns pointer to child geometry (for geometries with child geometries - i.e. geom.

childPoint

Returns point at index (for geometries without child geometries - i.e. curve / point).

clearCache

Clears any cached parameters associated with the geometry, e.g., bounding boxes

compareTo

Comparator for sorting of geometry.

convertTo

Converts the geometry to a specified type.

hasChildGeometries

Returns whether the geometry has any child geometries (False for point / curve, True otherwise)

hasCurvedSegments

Returns True if the geometry contains curved segments

isEmpty

Returns True if the geometry is empty

length

Returns the planar, 2-dimensional length of the geometry.

nCoordinates

Returns the number of nodes contained in the geometry

perimeter

Returns the planar, 2-dimensional perimeter of the geometry.

segmentize

Returns a version of the geometry without curves.

Attributes

FlagExportNanAsDoubleMin

FlagExportTrianglesAsPolygons

MaximumAngle

MaximumDifference

XY

YX

class qgis.core.QgsAbstractGeometry[source]

Bases: object

class AxisOrder

Bases: int

FlagExportNanAsDoubleMin = 2
FlagExportTrianglesAsPolygons = 1
MaximumAngle = 0
MaximumDifference = 1
class SegmentationToleranceType

Bases: int

class WkbFlag

Bases: int

class WkbFlags
class WkbFlags(f: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag)
class WkbFlags(a0: QgsAbstractGeometry.WkbFlags)

Bases: object

XY = 0
YX = 1
abstract addMValue(self, mValue: float = 0) bool[source]

Adds a measure to the geometry, initialized to a preset value.

Parameters:

mValue (float = 0) – initial m-value for all nodes

Return type:

bool

Returns:

True on success

See also

dropMValue()

See also

addZValue()

abstract addZValue(self, zValue: float = 0) bool[source]

Adds a z-dimension to the geometry, initialized to a preset value.

Parameters:

zValue (float = 0) – initial z-value for all nodes

Return type:

bool

Returns:

True on success

See also

dropZValue()

See also

addMValue()

abstract adjacentVertices(self, vertex: QgsVertexId)[source]

Returns the vertices adjacent to a specified vertex within a geometry.

Parameters:

vertex (QgsVertexId) -> (QgsVertexId)

virtual area(self) float[source]

Returns the planar, 2-dimensional area of the geometry.

Warning

QgsAbstractGeometry objects are inherently Cartesian/planar geometries, and the area returned by this method is calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for calculating the areas of geometries using geodesic calculations which account for the curvature of the Earth (or any other celestial body).

See also

length()

See also

perimeter()

Return type:

float

abstract asGml2(self, doc: QDomDocument, precision: int = 17, ns: str | None = '', axisOrder: QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) QDomElement[source]

Returns a GML2 representation of the geometry.

Parameters:
  • doc (QDomDocument) – DOM document

  • precision (int = 17) – number of decimal places for coordinates

  • ns (Optional[str] = '') – XML namespace

  • axisOrder (QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) – Axis order for generated GML

See also

asWkb()

See also

asWkt()

See also

asGml3()

See also

asJson()

Return type:

QDomElement

abstract asGml3(self, doc: QDomDocument, precision: int = 17, ns: str | None = '', axisOrder: QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) QDomElement[source]

Returns a GML3 representation of the geometry.

Parameters:
  • doc (QDomDocument) – DOM document

  • precision (int = 17) – number of decimal places for coordinates

  • ns (Optional[str] = '') – XML namespace

  • axisOrder (QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) – Axis order for generated GML

See also

asWkb()

See also

asWkt()

See also

asGml2()

See also

asJson()

Return type:

QDomElement

asJson(self, precision: int = 17) str[source]

Returns a GeoJSON representation of the geometry as a string.

Parameters:

precision (int = 17) – number of decimal places for coordinates

See also

asWkb()

See also

asWkt()

See also

asGml2()

See also

asGml3()

See also

asJsonObject()

Return type:

str

abstract asKml(self, precision: int = 17) str[source]

Returns a KML representation of the geometry.

Added in version 3.12.

Parameters:

precision (int = 17)

Return type:

str

abstract asQPainterPath(self) QPainterPath[source]

Returns the geometry represented as a QPainterPath.

Warning

not all geometry subclasses can be represented by a QPainterPath, e.g. points and multipoint geometries will return an empty path.

Added in version 3.16.

Return type:

QPainterPath

abstract asWkb(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) QByteArray[source]

Returns a WKB representation of the geometry.

The optional flags argument specifies flags controlling WKB export behavior (since QGIS 3.14).

See also

asWkt()

See also

asGml2()

See also

asGml3()

See also

asJson()

Parameters:

flags (Union[QgsAbstractGeometry.WkbFlags, QgsAbstractGeometry.WkbFlag] = QgsAbstractGeometry.WkbFlags())

Return type:

QByteArray

abstract asWkt(self, precision: int = 17) str[source]

Returns a WKT representation of the geometry.

Parameters:

precision (int = 17) – number of decimal places for coordinates

See also

asWkb()

See also

asGml2()

See also

asGml3()

See also

asJson()

Return type:

str

abstract boundary(self) QgsAbstractGeometry | None[source]

Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the geometry). For instance, a polygon geometry will have a boundary consisting of the linestrings for each ring in the polygon.

Return type:

Optional[QgsAbstractGeometry]

Returns:

boundary for geometry. May be None for some geometry types.

virtual boundingBox(self) QgsRectangle[source]

Returns the minimal bounding box for the geometry

Return type:

QgsRectangle

abstract boundingBox3D(self) QgsBox3D[source]

Returns the 3D bounding box for the geometry.

Added in version 3.34.

Return type:

QgsBox3D

virtual boundingBoxIntersects(self, rectangle: QgsRectangle) bool[source]

Returns True if the bounding box of this geometry intersects with a rectangle.

Since this test only considers the bounding box of the geometry, is is very fast to calculate and handles invalid geometries.

Added in version 3.20.

Parameters:

rectangle (QgsRectangle)

Return type:

bool

virtual boundingBoxIntersects(self, box3d: QgsBox3D) bool[source]

Returns True if the bounding box of this geometry intersects with a box3d.

Since this test only considers the bounding box of the geometry, is is very fast to calculate and handles invalid geometries.

Added in version 3.34.

Parameters:

box3d (QgsBox3D)

Return type:

bool

virtual calculateBoundingBox(self) QgsRectangle[source]

Default calculator for the minimal bounding box for the geometry. Derived classes should override this method if a more efficient bounding box calculation is available.

Return type:

QgsRectangle

virtual calculateBoundingBox3D(self) QgsBox3D[source]

Calculates the minimal 3D bounding box for the geometry.

Added in version 3.34.

Return type:

QgsBox3D

virtual centroid(self) QgsPoint[source]

Returns the centroid of the geometry

Return type:

QgsPoint

virtual childCount(self) int[source]

Returns number of child geometries (for geometries with child geometries) or child points (for geometries without child geometries - i.e. curve / point)

Note

used for vertex_iterator implementation

Return type:

int

virtual childGeometry(self, index: int) QgsAbstractGeometry | None[source]

Returns pointer to child geometry (for geometries with child geometries - i.e. geom. collection / polygon)

Note

used for vertex_iterator implementation

Parameters:

index (int)

Return type:

Optional[QgsAbstractGeometry]

virtual childPoint(self, index: int) QgsPoint[source]

Returns point at index (for geometries without child geometries - i.e. curve / point)

Note

used for vertex_iterator implementation

Parameters:

index (int)

Return type:

QgsPoint

abstract clear(self)[source]

Clears the geometry, ie reset it to a null geometry

virtual clearCache(self)[source]

Clears any cached parameters associated with the geometry, e.g., bounding boxes

abstract clone(self) QgsAbstractGeometry | None[source]

Clones the geometry by performing a deep copy

Return type:

Optional[QgsAbstractGeometry]

abstract closestSegment(self, pt: QgsPoint, epsilon: float = 4 * DBL_EPSILON)[source]

Searches for the closest segment of the geometry to a given point.

Parameters:
  • pt (QgsPoint) – specifies the point to find closest segment to

  • epsilon (float = 4*DBL_EPSILON) -> (float) – epsilon for segment snapping

Returns:

  • squared distance to closest segment or negative value on error

  • segmentPt: the closest point within the geometry

  • vertexAfter: the ID of the vertex at the end of the closest segment

  • leftOf: indicates whether the point lies on the left side of the geometry (-1 if point is to the left of the geometry, +1 if the point is to the right of the geometry, or 0 for cases where left/right could not be determined, e.g. point exactly on a line) False if point is to right of segment)

virtual compareTo(self, other: QgsAbstractGeometry | None) int[source]

Comparator for sorting of geometry.

Added in version 3.20.

Parameters:

other (Optional[QgsAbstractGeometry])

Return type:

int

abstract compareToSameClass(self, other: QgsAbstractGeometry | None) int[source]

Compares to an other geometry of the same class, and returns a integer for sorting of the two geometries.

Note

The actual logic for the sorting is an internal detail only and is subject to change between QGIS versions. The result should only be used for direct comparison of geometries and not stored for later use.

Added in version 3.20.

Parameters:

other (Optional[QgsAbstractGeometry])

Return type:

int

virtual convertTo(self, type: Qgis.WkbType) bool[source]

Converts the geometry to a specified type.

Return type:

bool

Returns:

True if conversion was successful

Parameters:

type (Qgis.WkbType)

abstract coordinateSequence(self) Any[source]

Retrieves the sequence of geometries, rings and nodes.

Return type:

Any

Returns:

coordinate sequence

abstract createEmptyWithSameType(self) QgsAbstractGeometry | None[source]

Creates a new geometry with the same class and same WKB type as the original and transfers ownership. To create it, the geometry is default constructed and then the WKB is changed.

See also

clone()

Return type:

Optional[QgsAbstractGeometry]

abstract deleteVertex(self, position: QgsVertexId) bool[source]

Deletes a vertex within the geometry

Parameters:

position (QgsVertexId) – vertex id for vertex to delete

Return type:

bool

Returns:

True if delete was successful

See also

insertVertex()

See also

moveVertex()

abstract dimension(self) int[source]

Returns the inherent dimension of the geometry. For example, this is 0 for a point geometry, 1 for a linestring and 2 for a polygon.

Return type:

int

abstract draw(self, p: QPainter)[source]

Draws the geometry using the specified QPainter.

Parameters:

p (QPainter) – destination QPainter

abstract dropMValue(self) bool[source]

Drops any measure values which exist in the geometry.

Return type:

bool

Returns:

True if m-values were present and have been removed

See also

addMValue()

See also

dropZValue()

abstract dropZValue(self) bool[source]

Drops any z-dimensions which exist in the geometry.

Return type:

bool

Returns:

True if Z values were present and have been removed

See also

addZValue()

See also

dropMValue()

abstract fromWkb(self, wkb: QgsConstWkbPtr) bool[source]

Sets the geometry from a WKB string. After successful read the wkb argument will be at the position where the reading has stopped.

See also

fromWkt()

Parameters:

wkb (QgsConstWkbPtr)

Return type:

bool

abstract fromWkt(self, wkt: str | None) bool[source]

Sets the geometry from a WKT string.

See also

fromWkb()

Parameters:

wkt (Optional[str])

Return type:

bool

abstract fuzzyDistanceEqual(self, other: QgsAbstractGeometry, epsilon: float = 1e-08) bool[source]

Performs fuzzy distance comparison between this geometry and other using an epsilon.

Traditionally, the comparison is done by examining the specific values (such as x and y) that define the location of vertices in the geometry. It focuses on the numerical differences or relationships between these values. On the other hand, comparing distances between points considers the actual spatial separation or length between the points, regardless of their coordinate values. This comparison involves measuring the distance between two points using formulas like the distance formula. Here, it’s the “distance comparison” (fuzzyDistanceEqual).

See also

fuzzyEqual()

See also

QgsGeometryUtilsBase.fuzzyEqual()

Added in version 3.36.

Parameters:
Return type:

bool

abstract fuzzyEqual(self, other: QgsAbstractGeometry, epsilon: float = 1e-08) bool[source]

Performs fuzzy comparison between this geometry and other using an epsilon.

The comparison is done by examining the specific values (such as x and y) that define the location of vertices in the geometry.

See also

QgsGeometryUtilsBase.fuzzyDistanceEqual()

Added in version 3.36.

Parameters:
Return type:

bool

abstract geometryType(self) str[source]

Returns a unique string representing the geometry type.

See also

wkbType()

See also

wktTypeStr()

Return type:

str

virtual hasChildGeometries(self) bool[source]

Returns whether the geometry has any child geometries (False for point / curve, True otherwise)

Note

used for vertex_iterator implementation

Return type:

bool

virtual hasCurvedSegments(self) bool[source]

Returns True if the geometry contains curved segments

Return type:

bool

abstract insertVertex(self, position: QgsVertexId, vertex: QgsPoint) bool[source]

Inserts a vertex into the geometry

Parameters:
  • position (QgsVertexId) – vertex id for position of inserted vertex

  • vertex (QgsPoint) – vertex to insert

Return type:

bool

Returns:

True if insert was successful

See also

moveVertex()

See also

deleteVertex()

is3D(self) bool[source]

Returns True if the geometry is 3D and contains a z-value.

See also

isMeasure()

Return type:

bool

virtual isEmpty(self) bool[source]

Returns True if the geometry is empty

Return type:

bool

isMeasure(self) bool[source]

Returns True if the geometry contains m values.

See also

is3D()

Return type:

bool

abstract isValid(self, flags: Qgis.GeometryValidityFlags | Qgis.GeometryValidityFlag = Qgis.GeometryValidityFlags())[source]

Checks validity of the geometry, and returns True if the geometry is valid.

Parameters:

flags (Union[Qgis.GeometryValidityFlags, Qgis.GeometryValidityFlag] = Qgis.GeometryValidityFlags()) -> (bool) – indicates optional flags which control the type of validity checking performed (corresponding to Qgis.GeometryValidityFlags).

Returns:

  • True if geometry is valid

  • error: the validity error message

Added in version 3.8.

virtual length(self) float[source]

Returns the planar, 2-dimensional length of the geometry.

Warning

QgsAbstractGeometry objects are inherently Cartesian/planar geometries, and the length returned by this method is calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for calculating the lengths of geometries using geodesic calculations which account for the curvature of the Earth (or any other celestial body).

See also

area()

See also

perimeter()

Return type:

float

abstract moveVertex(self, position: QgsVertexId, newPos: QgsPoint) bool[source]

Moves a vertex within the geometry

Parameters:
  • position (QgsVertexId) – vertex id for vertex to move

  • newPos (QgsPoint) – new position of vertex

Return type:

bool

Returns:

True if move was successful

See also

insertVertex()

See also

deleteVertex()

virtual nCoordinates(self) int[source]

Returns the number of nodes contained in the geometry

Return type:

int

abstract nextVertex(self, id: QgsVertexId)[source]

Returns next vertex id and coordinates

Parameters:

id (QgsVertexId) -> (bool) – initial value should be the starting vertex id. The next vertex id will be stored in this variable if found.

Returns:

  • False if at end

  • vertex: container for found node

abstract normalize(self)[source]

Reorganizes the geometry into a normalized form (or “canonical” form).

Polygon rings will be rearranged so that their starting vertex is the lower left and ring orientation follows the right hand rule, collections are ordered by geometry type, and other normalization techniques are applied. The resultant geometry will be geometrically equivalent to the original geometry.

Added in version 3.20.

abstract partCount(self) int[source]

Returns count of parts contained in the geometry.

See also

vertexCount()

See also

ringCount()

Return type:

int

parts(self) QgsGeometryPartIterator[source]

Returns Java-style iterator for traversal of parts of the geometry. This iterator can safely be used to modify parts of the geometry.

Example

# print the WKT representation of each part in a multi-point geometry
geometry = QgsMultiPoint.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
    print(part.asWkt())

# single part geometries only have one part - this loop will iterate once only
geometry = QgsLineString.fromWkt( 'LineString( 0 0, 10 10 )' )
for part in geometry.parts():
    print(part.asWkt())

# parts can be modified during the iteration
geometry = QgsMultiPoint.fromWkt( 'MultiPoint( 0 0, 1 1, 2 2)' )
for part in geometry.parts():
    part.transform(ct)

# part iteration can also be combined with vertex iteration
geometry = QgsMultiPolygon.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' )
for part in geometry.parts():
    for v in part.vertices():
        print(v.x(), v.y())

See also

vertices()

Added in version 3.6.

Return type:

QgsGeometryPartIterator

virtual perimeter(self) float[source]

Returns the planar, 2-dimensional perimeter of the geometry.

Warning

QgsAbstractGeometry objects are inherently Cartesian/planar geometries, and the perimeter returned by this method is calculated using strictly Cartesian mathematics. In contrast, the QgsDistanceArea class exposes methods for calculating the perimeters of geometries using geodesic calculations which account for the curvature of the Earth (or any other celestial body).

See also

area()

See also

length()

Return type:

float

abstract removeDuplicateNodes(self, epsilon: float = 4 * DBL_EPSILON, useZValues: bool = False) bool[source]

Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerate geometry.

The epsilon parameter specifies the tolerance for coordinates when determining that vertices are identical.

By default, z values are not considered when detecting duplicate nodes. E.g. two nodes with the same x and y coordinate but different z values will still be considered duplicate and one will be removed. If useZValues is True, then the z values are also tested and nodes with the same x and y but different z will be maintained.

Note that duplicate nodes are not tested between different parts of a multipart geometry. E.g. a multipoint geometry with overlapping points will not be changed by this method.

The function will return True if nodes were removed, or False if no duplicate nodes were found.

Parameters:
  • epsilon (float = 4*DBL_EPSILON)

  • useZValues (bool = False)

Return type:

bool

abstract ringCount(self, part: int = 0) int[source]

Returns the number of rings of which this geometry is built.

Parameters:

part (int = 0)

Return type:

int

abstract segmentLength(self, startVertex: QgsVertexId) float[source]

Returns the length of the segment of the geometry which begins at startVertex.

Warning

QgsAbstractGeometry objects are inherently Cartesian/planar geometries, and the lengths returned by this method are calculated using strictly Cartesian mathematics.

Parameters:

startVertex (QgsVertexId)

Return type:

float

virtual segmentize(self, tolerance: float = M_PI / 180, toleranceType: QgsAbstractGeometry.SegmentationToleranceType = QgsAbstractGeometry.MaximumAngle) QgsAbstractGeometry | None[source]

Returns a version of the geometry without curves. Caller takes ownership of the returned geometry.

Parameters:
  • tolerance (float = M_PI/180) – segmentation tolerance

  • toleranceType (QgsAbstractGeometry.SegmentationToleranceType = QgsAbstractGeometry.MaximumAngle) – maximum segmentation angle or maximum difference between approximation and curve

Return type:

Optional[QgsAbstractGeometry]

setZMTypeFromSubGeometry(self, subggeom: QgsAbstractGeometry | None, baseGeomType: Qgis.WkbType)[source]

Updates the geometry type based on whether sub geometries contain z or m values.

Parameters:
simplifiedTypeRef(self) QgsAbstractGeometry | None[source]

Returns a reference to the simplest lossless representation of this geometry, e.g. if the geometry is a multipart geometry type with a single member geometry, a reference to that part will be returned.

This method employs the following logic:

  • For multipart geometries containing a single part only a direct reference to that part will be returned.

  • For compound curve geometries containing a single curve only a direct reference to that curve will be returned.

This method returns a reference only, and does not involve any geometry cloning.

Note

Ownership of the returned geometry is NOT transferred, and remains with the original geometry object. Callers must take care to ensure that the original geometry object exists for the lifespan of the returned object.

Added in version 3.20.

Return type:

Optional[QgsAbstractGeometry]

abstract simplifyByDistance(self, tolerance: float) QgsAbstractGeometry | None[source]

Simplifies the geometry by applying the Douglas Peucker simplification by distance algorithm.

The caller takes ownership of the returned geometry. Curved geometries will be segmentized prior to simplification.

If a simplified geometry cannot be calculated None will be returned.

The returned geometry may be invalid and contain self-intersecting rings.

Added in version 3.38.

Parameters:

tolerance (float)

Return type:

Optional[QgsAbstractGeometry]

abstract snappedToGrid(self, hSpacing: float, vSpacing: float, dSpacing: float = 0, mSpacing: float = 0, removeRedundantPoints: bool = False) QgsAbstractGeometry | None[source]

Makes a new geometry with all the points or vertices snapped to the closest point of the grid. Ownership is transferred to the caller.

If the gridified geometry could not be calculated None will be returned. It may generate an invalid geometry (in some corner cases). It can also be thought as rounding the edges and it may be useful for removing errors.

Example:

geometry.snappedToGrid(1, 1)

In this case we use a 2D grid of 1x1 to gridify. In this case, it can be thought like rounding the x and y of all the points/vertices to full units (remove all decimals).

Parameters:
  • hSpacing (float) – Horizontal spacing of the grid (x axis). 0 to disable.

  • vSpacing (float) – Vertical spacing of the grid (y axis). 0 to disable.

  • dSpacing (float = 0) – Depth spacing of the grid (z axis). 0 (default) to disable.

  • mSpacing (float = 0) – Custom dimension spacing of the grid (m axis). 0 (default) to disable.

  • removeRedundantPoints (bool = False) – if True, then points which are redundant (e.g. they represent mid points on a straight line segment) will be skipped (since QGIS 3.38)

Return type:

Optional[QgsAbstractGeometry]

sortIndex(self) int[source]

Returns the sort index for the geometry, used in the compareTo() method to compare geometries of different types.

Added in version 3.20.

Return type:

int

abstract swapXy(self)[source]

Swaps the x and y coordinates from the geometry. This can be used to repair geometries which have accidentally had their latitude and longitude coordinates reversed.

Added in version 3.2.

abstract toCurveType(self) QgsAbstractGeometry | None[source]

Returns the geometry converted to the more generic curve type. E.g. QgsLineString -> QgsCompoundCurve, QgsPolygon -> QgsCurvePolygon, QgsMultiLineString -> QgsMultiCurve, QgsMultiPolygon -> QgsMultiSurface

Return type:

Optional[QgsAbstractGeometry]

Returns:

the converted geometry. Caller takes ownership

abstract transform(self, ct: QgsCoordinateTransform, d: Qgis.TransformDirection = Qgis.TransformDirection.Forward, transformZ: bool = False)[source]

Transforms the geometry using a coordinate transform

Parameters:
  • ct (QgsCoordinateTransform) – coordinate transform

  • d (Qgis.TransformDirection = Qgis.TransformDirection.Forward) – transformation direction

  • transformZ (bool = False) – set to True to also transform z coordinates. This requires that the z coordinates in the geometry represent height relative to the vertical datum of the source CRS (generally ellipsoidal heights) and are expressed in its vertical units (generally meters). If False, then z coordinates will not be changed by the transform.

abstract transform(self, t: QTransform, zTranslate: float = 0, zScale: float = 1, mTranslate: float = 0, mScale: float = 1)[source]

Transforms the x and y components of the geometry using a QTransform object t.

Optionally, the geometry’s z values can be scaled via zScale and translated via zTranslate. Similarly, m-values can be scaled via mScale and translated via mTranslate.

Parameters:
  • t (QTransform)

  • zTranslate (float = 0)

  • zScale (float = 1)

  • mTranslate (float = 0)

  • mScale (float = 1)

abstract transform(self, transformer: QgsAbstractGeometryTransformer | None, feedback: QgsFeedback | None = None) bool[source]

Transforms the vertices from the geometry in place, using the specified geometry transformer object.

Depending on the transformer used, this may result in an invalid geometry.

The optional feedback argument can be used to cancel the transformation before it completes. If this is done, the geometry will be left in a semi-transformed state.

Return type:

bool

Returns:

True if the geometry was successfully transformed.

Added in version 3.18.

Parameters:
abstract vertexAngle(self, vertex: QgsVertexId) float[source]

Returns approximate angle at a vertex. This is usually the average angle between adjacent segments, and can be pictured as the orientation of a line following the curvature of the geometry at the specified vertex.

Parameters:

vertex (QgsVertexId) – the vertex id

Return type:

float

Returns:

rotation in radians, clockwise from north

abstract vertexAt(self, id: QgsVertexId) QgsPoint[source]

Returns the point corresponding to a specified vertex id

Parameters:

id (QgsVertexId)

Return type:

QgsPoint

abstract vertexCount(self, part: int = 0, ring: int = 0) int[source]

Returns the number of vertices of which this geometry is built.

Parameters:
  • part (int = 0)

  • ring (int = 0)

Return type:

int

abstract vertexNumberFromVertexId(self, id: QgsVertexId) int[source]

Returns the vertex number corresponding to a vertex id.

The vertex numbers start at 0, so a return value of 0 corresponds to the first vertex.

Returns -1 if a corresponding vertex could not be found.

Parameters:

id (QgsVertexId)

Return type:

int

vertices(self) QgsVertexIterator[source]

Returns a read-only, Java-style iterator for traversal of vertices of all the geometry, including all geometry parts and rings.

Warning

The iterator returns a copy of individual vertices, and accordingly geometries cannot be modified using the iterator. See transformVertices() for a safe method to modify vertices “in-place”.

Example

# print the x and y coordinate for each vertex in a LineString
geometry = QgsLineString.fromWkt( 'LineString( 0 0, 1 1, 2 2)' )
for v in geometry.vertices():
    print(v.x(), v.y())

# vertex iteration includes all parts and rings
geometry = QgsMultiPolygon.fromWkt( 'MultiPolygon((( 0 0, 0 10, 10 10, 10 0, 0 0 ),( 5 5, 5 6, 6 6, 6 5, 5 5)),((20 2, 22 2, 22 4, 20 4, 20 2)))' )
for v in geometry.vertices():
    print(v.x(), v.y())

See also

parts()

Return type:

QgsVertexIterator

abstract wkbSize(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) int[source]

Returns the length of the QByteArray returned by asWkb()

The optional flags argument specifies flags controlling WKB export behavior

Added in version 3.16.

Parameters:

flags (Union[QgsAbstractGeometry.WkbFlags, QgsAbstractGeometry.WkbFlag] = QgsAbstractGeometry.WkbFlags())

Return type:

int

wkbType(self) Qgis.WkbType[source]

Returns the WKB type of the geometry.

See also

geometryType()

See also

wktTypeStr()

Return type:

Qgis.WkbType

wktTypeStr(self) str[source]

Returns the WKT type string of the geometry.

See also

geometryType()

See also

wkbType()

Return type:

str