3

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()
 break
 if id != -1:
 print feats[id].attribute('name')
 else:
 print "no feature selected"
canvas = iface.mapCanvas()
pointTool = QgsMapToolEmitPoint(canvas)
pointTool.canvasClicked.connect(display_point)
canvas.setMapTool(pointTool)
Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Jul 25, 2018 at 12:48

1 Answer 1

0

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

sourceLayer.getSelectedFeatures()

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

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.