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]

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

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

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


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

    newgeom = QgsGeometry.fromMultiPolylineXY(mls)

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?


1 Answer 1


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)    


newgeom = QgsGeometry(mls)    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.