I have an empty layer in QGIS in that i just want to draw a polyline by selecting points on layer using Python.

For example, if I select a start point and endpoint on a layer, I want to draw a line connecting to those points using Python code. I have gone through all related references but I didn't get it.

What I have tried is:

from qgis.gui import QgsMapToolEmitPoint

def display_point(point, mouse_button):
  coords = "Map Coordinates: {:.4f}, {:.4f}".format(point.x(), point.y())
  print coords
  layer = iface.activeLayer()
  feats = [ feat for feat in layer.getFeatures() ]
  geo_pt = QgsGeometry.fromPoint(QgsPoint(point.x(), point.y()))
  id = -1

  for feat in feats:
    if geo_pt.within(feat.geometry()):
      id = feat.id()

  if id != -1:
    print feats[id].attribute('name')
    print "no feature selected"

canvas = iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)

1 Answer 1


You could try to identify the selected features of the source layer with


and then create a line geometry from the list of points:

line = QgsGeometry.fromPolyline(list_of_points)
  • I got this error : AttributeError: 'QgsVectorLayer' object has no attribute 'getSelectedFeatures'
    – Virat ABD
    Aug 23, 2018 at 6:27
  • @ViratABD You probably use QGIS 2.x. getSelectedFeatures method is not defined in QGIS 2.x API. Use selectedFeaturesIterator for the same purpose. Oct 14, 2022 at 8:49

Your Answer

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

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