Class: QgsAbstractGeometry

class qgis.core.QgsAbstractGeometry

Bases: sip.wrapper

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.

QgsAbstractGeometry() Constructor for QgsAbstractGeometry.

QgsAbstractGeometry(geom: QgsAbstractGeometry)

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.

area

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

asGml2

Returns a GML2 representation of the geometry.

asGml3

Returns a GML3 representation of the geometry.

asJson

Returns a GeoJSON representation of the geometry as a QString.

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).

boundingBox

Returns the minimal bounding box for the geometry

boundingBox3D

Returns the 3D 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).

clear

Clears the geometry, ie reset it to a null geometry

clearCache

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

clone

Clones the geometry by performing a deep copy

closestSegment

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

compareTo

Comparator for sorting of geometry.

compareToSameClass

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

convertTo

Converts the geometry to a specified type.

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.

hasChildGeometries

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

hasCurvedSegments

Returns True if the geometry contains curved segments

insertVertex

Inserts a vertex into the geometry

is3D

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

isEmpty

Returns True if the geometry is empty

isMeasure

Returns True if the geometry contains m values.

isValid

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

length

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

moveVertex

Moves a vertex within the geometry

nCoordinates

Returns the number of nodes contained in 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.

parts

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

perimeter

Returns the planar, 2-dimensional perimeter of 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.

segmentize

Returns a version of the geometry without curves.

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.

snappedToGrid

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

sortIndex

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

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.

vertices

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

wkbSize

Returns the length of the QByteArray returned by asWkb()

wkbType

Returns the WKB type of the geometry.

wktTypeStr

Returns the WKT type string of the geometry.

Attributes

FlagExportNanAsDoubleMin

FlagExportTrianglesAsPolygons

MaximumAngle

MaximumDifference

XY

YX

staticMetaObject

class AxisOrder

Bases: int

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

Bases: int

baseClass

alias of QgsAbstractGeometry

class WkbFlag

Bases: int

class WkbFlags
class WkbFlags(Union[QgsAbstractGeometry.WkbFlags, QgsAbstractGeometry.WkbFlag])
class WkbFlags(QgsAbstractGeometry.WkbFlags)

Bases: sip.wrapper

XY = 0
YX = 1
addMValue(self, mValue: float = 0) bool

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()

addZValue(self, zValue: float = 0) bool

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()

adjacentVertices(self, vertex: QgsVertexId) Tuple[QgsVertexId, QgsVertexId]

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

Parameters:

vertex (QgsVertexId) –

Return type:

Tuple[QgsVertexId, QgsVertexId]

area(self) float

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

asGml2(self, doc: QDomDocument, precision: int = 17, ns: str = '', axisOrder: QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) QDomElement

Returns a GML2 representation of the geometry.

Parameters:
  • doc (QDomDocument) – DOM document

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

  • ns (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

asGml3(self, doc: QDomDocument, precision: int = 17, ns: str = '', axisOrder: QgsAbstractGeometry.AxisOrder = QgsAbstractGeometry.AxisOrder.XY) QDomElement

Returns a GML3 representation of the geometry.

Parameters:
  • doc (QDomDocument) – DOM document

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

  • ns (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

Returns a GeoJSON representation of the geometry as a QString.

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

asKml(self, precision: int = 17) str

Returns a KML representation of the geometry.

New in version 3.12.

Parameters:

precision (int = 17) –

Return type:

str

asQPainterPath(self) QPainterPath

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.

New in version 3.16.

Return type:

QPainterPath

asWkb(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) QByteArray

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) –

Return type:

QByteArray

asWkt(self, precision: int = 17) str

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

boundary(self) QgsAbstractGeometry

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:

QgsAbstractGeometry

Returns:

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

boundingBox(self) QgsRectangle

Returns the minimal bounding box for the geometry

Return type:

QgsRectangle

boundingBox3D(self) QgsBox3D

Returns the 3D bounding box for the geometry.

New in version 3.34.

Return type:

QgsBox3D

boundingBoxIntersects(self, rectangle: QgsRectangle) bool

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.

New in version 3.20.

boundingBoxIntersects(self, box3d: QgsBox3D) -> bool 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.

New in version 3.34.

Parameters:

rectangle (QgsRectangle) –

Return type:

bool

calculateBoundingBox(self) QgsRectangle

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

calculateBoundingBox3D(self) QgsBox3D

Calculates the minimal 3D bounding box for the geometry.

New in version 3.34.

Return type:

QgsBox3D

centroid(self) QgsPoint

Returns the centroid of the geometry

Return type:

QgsPoint

childCount(self) int

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

childGeometry(self, index: int) QgsAbstractGeometry

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:

QgsAbstractGeometry

childPoint(self, index: int) QgsPoint

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

clear(self)

Clears the geometry, ie reset it to a null geometry

clearCache(self)

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

clone(self) QgsAbstractGeometry

Clones the geometry by performing a deep copy

Return type:

QgsAbstractGeometry

closestSegment(self, pt: QgsPoint, epsilon: float = 4 * DBL_EPSILON) Tuple[float, QgsPoint, QgsVertexId, int]

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

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

  • segmentPt – storage for the closest point within the geometry

  • vertexAfter – storage for the ID of the vertex at the end of the closest segment

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

Return type:

Tuple[float, QgsPoint, QgsVertexId, int]

Returns:

  • squared distance to closest segment or negative value on error

  • 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)

compareTo(self, other: QgsAbstractGeometry) int

Comparator for sorting of geometry.

New in version 3.20.

Parameters:

other (QgsAbstractGeometry) –

Return type:

int

compareToSameClass(self, other: QgsAbstractGeometry) int

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.

New in version 3.20.

Parameters:

other (QgsAbstractGeometry) –

Return type:

int

convertTo(self, type: Qgis.WkbType) bool

Converts the geometry to a specified type.

Return type:

bool

Returns:

True if conversion was successful

Parameters:

type (Qgis.WkbType) –

coordinateSequence(self) object

Retrieves the sequence of geometries, rings and nodes.

Return type:

object

Returns:

coordinate sequence

createEmptyWithSameType(self) QgsAbstractGeometry

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:

QgsAbstractGeometry

deleteVertex(self, position: QgsVertexId) bool

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()

dimension(self) int

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

draw(self, p: QPainter)

Draws the geometry using the specified QPainter.

Parameters:

p (QPainter) – destination QPainter

dropMValue(self) bool

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()

dropZValue(self) bool

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()

fromWkb(self, wkb: QgsConstWkbPtr) bool

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

fromWkt(self, wkt: str) bool

Sets the geometry from a WKT string.

See also

fromWkb()

Parameters:

wkt (str) –

Return type:

bool

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

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()

New in version 3.36.

Parameters:
Return type:

bool

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

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()

New in version 3.36.

Parameters:
Return type:

bool

geometryType(self) str

Returns a unique string representing the geometry type.

See also

wkbType()

See also

wktTypeStr()

Return type:

str

hasChildGeometries(self) bool

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

Note

used for vertex_iterator implementation

Return type:

bool

hasCurvedSegments(self) bool

Returns True if the geometry contains curved segments

Return type:

bool

insertVertex(self, position: QgsVertexId, vertex: QgsPoint) bool

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

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

See also

isMeasure()

Return type:

bool

isEmpty(self) bool

Returns True if the geometry is empty

Return type:

bool

isMeasure(self) bool

Returns True if the geometry contains m values.

See also

is3D()

Return type:

bool

isValid(self, flags: Qgis.GeometryValidityFlags | Qgis.GeometryValidityFlag = Qgis.GeometryValidityFlags()) Tuple[bool, str]

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

Parameters:

flags (Union[Qgis.GeometryValidityFlags) – indicates optional flags which control the type of validity checking performed (corresponding to Qgis.GeometryValidityFlags).

Return type:

Tuple[bool, str]

Returns:

  • True if geometry is valid

  • error: will be set to the validity error message

New in version 3.8.

length(self) float

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

moveVertex(self, position: QgsVertexId, newPos: QgsPoint) bool

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()

nCoordinates(self) int

Returns the number of nodes contained in the geometry

Return type:

int

nextVertex(self, id: QgsVertexId) Tuple[bool, QgsPoint]

Returns next vertex id and coordinates

Parameters:

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

Return type:

Tuple[bool, QgsPoint]

Returns:

  • False if at end

  • vertex: container for found node

normalize(self)

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.

New in version 3.20.

partCount(self) int

Returns count of parts contained in the geometry.

See also

vertexCount()

See also

ringCount()

Return type:

int

parts(self) QgsGeometryPartIterator

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()

New in version 3.6.

Return type:

QgsGeometryPartIterator

perimeter(self) float

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

removeDuplicateNodes(self, epsilon: float = 4 * DBL_EPSILON, useZValues: bool = False) bool

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

ringCount(self, part: int = 0) int

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

Parameters:

part (int = 0) –

Return type:

int

segmentLength(self, startVertex: QgsVertexId) float

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

segmentize(self, tolerance: float = M_PI / 180, toleranceType: QgsAbstractGeometry.SegmentationToleranceType = QgsAbstractGeometry.MaximumAngle) QgsAbstractGeometry

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:

QgsAbstractGeometry

setZMTypeFromSubGeometry(self, subggeom: QgsAbstractGeometry, baseGeomType: Qgis.WkbType)

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

Parameters:
simplifiedTypeRef(self) QgsAbstractGeometry

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.

New in version 3.20.

Return type:

QgsAbstractGeometry

snappedToGrid(self, hSpacing: float, vSpacing: float, dSpacing: float = 0, mSpacing: float = 0) QgsAbstractGeometry

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.

Return type:

QgsAbstractGeometry

sortIndex(self) int

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

New in version 3.20.

Return type:

int

staticMetaObject = <PyQt5.QtCore.QMetaObject object>
swapXy(self)

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.

New in version 3.2.

toCurveType(self) QgsAbstractGeometry

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

Return type:

QgsAbstractGeometry

Returns:

the converted geometry. Caller takes ownership

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

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.

transform(self, t: QTransform, zTranslate: float = 0, zScale: float = 1, mTranslate: float = 0, mScale: float = 1) 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.

transform(self, transformer: QgsAbstractGeometryTransformer, feedback: QgsFeedback = None) -> bool 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.

Returns:

True if the geometry was successfully transformed.

New in version 3.18.

vertexAngle(self, vertex: QgsVertexId) float

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

vertexAt(self, id: QgsVertexId) QgsPoint

Returns the point corresponding to a specified vertex id

Parameters:

id (QgsVertexId) –

Return type:

QgsPoint

vertexCount(self, part: int = 0, ring: int = 0) int

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

Parameters:
  • part (int = 0) –

  • ring (int = 0) –

Return type:

int

vertexNumberFromVertexId(self, id: QgsVertexId) int

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

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

wkbSize(self, flags: QgsAbstractGeometry.WkbFlags | QgsAbstractGeometry.WkbFlag = QgsAbstractGeometry.WkbFlags()) int

Returns the length of the QByteArray returned by asWkb()

The optional flags argument specifies flags controlling WKB export behavior

New in version 3.16.

Parameters:

flags (Union[QgsAbstractGeometry.WkbFlags) –

Return type:

int

wkbType(self) Qgis.WkbType

Returns the WKB type of the geometry.

See also

geometryType()

See also

wktTypeStr()

Return type:

Qgis.WkbType

wktTypeStr(self) str

Returns the WKT type string of the geometry.

See also

geometryType()

See also

wkbType()

Return type:

str