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)
1 Answer 1
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)
-
I got this error : AttributeError: 'QgsVectorLayer' object has no attribute 'getSelectedFeatures'Virat ABD– Virat ABD2018年08月23日 06:27:14 +00:00Commented Aug 23, 2018 at 6:27
-
1@ViratABD You probably use QGIS 2.x.
getSelectedFeatures
method is not defined in QGIS 2.x API. UseselectedFeaturesIterator
for the same purpose.Kadir Şahbaz– Kadir Şahbaz2022年10月14日 08:49:39 +00:00Commented Oct 14, 2022 at 8:49
Explore related questions
See similar questions with these tags.