5

In QGIS GUI, a line feature is created using this icon

LineFeature

How to create a line with a fixed distance from a vector layer using PyQGIS.

This my example:

from qgis.core import *
from qgis.PyQt.QtCore import QVariant

capa = QgsVectorLayer("Point?crs=epsg:32718", "temp", "memory")

pr = capa.dataProvider() pr.addAttributes([ QgsField("codigo", QVariant.Int), QgsField("nombre", QVariant.String)]) capa.updateFields() ...

In Toolbars / mDigitizeToolBar the is action mActionAddFeatures this create a line feature, i need how to call from Python Console, with parameters.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
leotv
  • 439
  • 6
  • 10

1 Answers1

6

You can add a LineString to a vector layer with PyQGIS 3 with the following code:

# Your code
from qgis.core import *
from qgis.PyQt.QtCore import QVariant

capa = QgsVectorLayer("LineString?crs=epsg:32718", "temp", "memory")

pr = capa.dataProvider() pr.addAttributes([ QgsField("codigo", QVariant.Int), QgsField("nombre", QVariant.String)]) capa.updateFields()

Add the layer in QGIS project

QgsProject.instance().addMapLayer(capa)

Start editing layer

capa.startEditing() feat = QgsFeature(capa.fields()) # Create the feature feat.setAttribute("codigo", 12) # set attributes feat.setAttribute("nombre", "twelve")

Create HERE the line you want with the 2 xy coordinates

feat.setGeometry(QgsGeometry.fromPolylineXY([QgsPointXY(12, 12), QgsPointXY(300, 300)]))

capa.addFeature(feat) # add the feature to the layer capa.endEditCommand() # Stop editing capa.commitChanges() # Save changes

Note: I had to correct your code where you put Point instead of LineString as the layer geometry type:

capa = QgsVectorLayer("LineString?crs=epsg:32718", "temp", "memory")
Taras
  • 32,823
  • 4
  • 66
  • 137
Djedouas
  • 131
  • 3