I have a Polyline and would like to add new vertex to before start point or end point or at any part of the polyline using python in qgis.

How can i do that?


First case: insert new polyline

You have to define the Polyline like so:

pLine = [QgsPoint(1,1), QgsPoint(2,1), QgsPoint(2,2)]

it is a list-of-QgsPoint. After you can put more QgsPoint into the list by append to insert the element at the end of the list:


or inserting some vertex point at a specific location of the list:

## insert value at index 1
pLine.insert(1, QgsPoint(1, 0.5))

in this case the result will be:

pLine = [QgsPoint(1,1), QgsPoint(1, 0.5), QgsPoint(2,1), QgsPoint(2,2), QgsPoint(3,2)]

To add the new feature to the layer:

## create and add to map canvas a memory layer
lineLayer = iface.addVectorLayer("LineString", "Line Layer", "memory")

## create a feature
ft = QgsFeature()
## get geometry from the list-of-QgsPoint
polyline = QgsGeometry.fromPolyline(pLine)
## set geometry to the feature

pr = lineLayer.dataProvider()

Second case: change an existing polyline

To change an existing geometry e.g adding a new vertex to line:

## add element to the list-of-Qgspoint at index 2
pLine.insert(2, QgsPoint(2, 0.5))
## define geometry with the new vertex
polyline = QgsGeometry.fromPolyline(pLine)
## change the geometry

in order to display the new vertex you have to refresh the map canvas:

  • when i am changing the geometry values after inserting the vertex it is creating a new layer for me. But i want to make changes in the same layer. – user99 Sep 12 '17 at 9:09
  • @Irssvt I just want to insert vertex but when i am inserting the vertex my line is getting snapped but i dont want snapping and just i want to place the vertex. How can i do that – user99 Nov 27 '17 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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