[QGIS-Developer] Geometry operations in Python

Daan Goedkoop dgoedkoop at gmx.net
Wed Jan 24 02:11:25 PST 2018


Hello all,

I'm updating my plugin to QGIS 3.

It sometimes needs to reverse line directions. I used to do it like this:

return QgsGeometry.fromPolyline(geom.asPolyline().reverse())

Q1. Do I understand it correctly, that fromPolyline returns a
QgsPointXY list, thus destroying any M/Z values?

What I do now, and what seems to work, is this:

return QgsGeometry(geom.constGet().reversed())

Q2. Is this the preferred way?
Q3. Is it better to use constGet() or normal get()?

The second issue are multi-part geometries. I have tried something
like this, after selecting a simple line in a .shp layer:

>> qgis.utils.iface.activeLayer().selectedFeatures()[0].geometry().constGet().wkbType()
5 (note: multipart line. I don't understand why, but ok)
>> qgis.utils.iface.activeLayer().selectedFeatures()[0].geometry().constGet().numGeometries()
0
>> qgis.utils.iface.activeLayer().selectedFeatures()[0].geometry().constGet().geometryN(0)
<crashes QGIS entirely>

So apparently this doesn't work. So now I use an approach like this:

list = qgis.utils.iface.activeLayer().selectedFeatures()[0].geometry().asGeometryCollection()
mls = QgsMultiLineString()
for line in list:
   mls.addGeometry(line.constGet().reversed())
newgeom = QgsGeometry(mls)

Q4. Is this the recommended way of doing things?

Can someone shed a light on this?

Kind regards,
Daan


More information about the QGIS-Developer mailing list