# How can I create a line with three points with Python in QGIS?

I'm new to Python and I'm having some dificulties. I want to create a simple layer with a line in the console of QGIS with Python. How can I do that?

-
Are you trying to do something different than what you asked in another question? gis.stackexchange.com/questions/60007/… – user3461 May 9 '13 at 14:28
Yes because I whant to make an action with python – user1573901 May 9 '13 at 14:33

You must first understand how PyQGIS handles geometry (Geometry Handling)

The most important element is the point:

QgsPoint(x,y)

and a line or a segment of line are composed of two points:

QgsGeometry.fromPolyline([QgsPoint(x1,y1),QgsPoint(x2,y2)]));

So to construct a line:

``````line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
line = QgsGeometry.fromPolyline([line_start,line_end])
``````

and with a memory layer (geometry only, without the attributes):

``````# create a new memory layer
v_layer = QgsVectorLayer("LineString", "line", "memory")
pr = v_layer.dataProvider()
# create a new feature
seg = QgsFeature()
# add the geometry to the feature,
seg.setGeometry(QgsGeometry.fromPolyline([line_start, line_end]))
# ...it was here that you can add attributes, after having defined....
# add the geometry to the layer
# update extent of the layer (not necessary)
v_layer.updateExtents()
# show the line
``````

the result is:

with 3 points, just add it as a new feature:

``````newpoint = QgsPoint(143,125)
v_layer = QgsVectorLayer("LineString", "line_3pt", "memory")
pr = v_layer.dataProvider()
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([line_start, line_end]))
# new feature: line from line_end to newpoint
seg = QgsFeature()
seg.setGeometry(QgsGeometry.fromPolyline([line_end, newpoint]))