Trước tiên bạn phải hiểu cách PyQGIS xử lý hình học ( Xử lý hình học )
Yếu tố quan trọng nhất là điểm:
QssPoint (x, y)
và một dòng hoặc một đoạn của dòng bao gồm hai điểm:
QssGeometry.fromPolyline ([QssPoint (x1, y1), QssPoint (x2, y2)]));
Vì vậy, để xây dựng một dòng:
line_start = QgsPoint(50,50)
line_end = QgsPoint(100,150)
line = QgsGeometry.fromPolyline([line_start,line_end])
và với một lớp bộ nhớ (chỉ hình học, không có thuộc tính):
# 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
pr.addFeatures( [ seg ] )
# update extent of the layer (not necessary)
v_layer.updateExtents()
# show the line
QgsMapLayerRegistry.instance().addMapLayers([v_layer])
kết quả là:

với 3 điểm, chỉ cần thêm nó như một tính năng mới:
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]))
pr.addFeatures( [ seg ] )
v_layer.updateExtents()
# add the line to
QgsMapLayerRegistry.instance().addMapLayers([v_layer])
và kết quả là:

Và với vòng lặp for, bạn có thể tạo một dòng có nhiều phân đoạn:
