6

I'm new to PyQGIS and I'm having some dificulties. I'm trying to implement / utilize "Add Feature" (polyline) functionality in my python plugin. I know I can do this by defining starting and ending points.

PyQGIS, construct a polyline:

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

This is what I'm trying to avoid. I'd like user to digitize / create polyline by clicking on map canvas to preview geometry. How can I do that?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Sep 19, 2016 at 1:17
2
  • Do you want to enable an edit session over a polyline layer you already have or do you want to allow the user to digitize a temporal polyline (e.g, like the one you can see while measuring distances) on map canvas? Commented Sep 19, 2016 at 12:37
  • @GermánCarrillo . Yes, I want to digitize / edit on the existing polyline layer on map canvas (not the temporal polyline). Commented Sep 20, 2016 at 1:02

1 Answer 1

3

You can start an edit session on your line layer and activate the Add Feature tool by including this code in your plugin:

layer = self.iface.activeLayer() # See the note below...
layer.startEditing()
self.iface.actionAddFeature().trigger()

NOTE: the way you access the line layer might differ in your case. You could, for instance, get the layer by name (if it's already loaded into QGIS) or even load it by yourself, providing a URI, name, and data provider.

If you want to save the edits made to the line layer also from your plugin, you can call:

layer.commitChanges()

On the other hand, if you want to revert any edit made on the layer since you called startEditing(), you can call:

layer.rollBack()

Hope it helps!

answered Sep 20, 2016 at 1:21
2
  • What do you think about QgsRubberBand for drawing polyline and polygon? docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/… Commented Sep 29, 2016 at 7:03
  • If you need a temporal geometry on the screen, QgsRubberBand is a great alternative. Everything depends on what you actually need. Commented Sep 29, 2016 at 12:28

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.