PyQGIS – Fixing TypeError When Converting QgsMultiLineString to QgsGeometry

geometry-conversionlinestringmultipartpyqgis

I have previously written some PyQGIS code to replace the features in a LineString layer with new features. The outline of the code is below – I have left out the specific code to create data for the LineString. This code works fine.

layers = QgsProject.instance().mapLayersByName('LayerToChange')
layer = layers[0]
layer.startEditing()

for f in layer.getFeatures():
    ls = QgsLineString()

    #### Replace with code to populate LineString with data

    newgeom = QgsGeometry.fromPolyline(ls)
    layer.changeGeometry(f.id(), newgeom)

layer.commitChanges()

I am now looking to extend this to cater for MultiLineStrings. This seems straightforward enough, up until the point at which we need to create a QgsGeometry object from the MultiLineString.

for f in layer.getFeatures():
    geom = f.geometry().constGet()
    mls = QgsMultiLineString()
    for l in geom:
        ls = QgsLineString()

        #### Replace with code to populate LineString with data

        mls.addGeometry(ls)
    newgeom = QgsGeometry.fromMultiPolylineXY(mls)
    
    layer.changeGeometry(f.id(),newgeom)

While QgsGeometry.fromPolyline will create a geometry from a LineString, QgsGeometry.fromMultiPolylineXY throws an error:

TypeError: QgsGeometry.fromMultiPolylineXY(): argument 1 has unexpected type 'QgsMultiLineString'

Can someone suggest a fix?

Best Answer

QgsMultiLineString is a child class of QgsAbstractGeometry which can be used to create a QgsGeometry using the following constructor QgsGeometry(QgsAbstractGeometry geom)

This means that you can replace:

newgeom = QgsGeometry.fromMultiPolylineXY(mls)    

with:

newgeom = QgsGeometry(mls)