[GIS] Creating a Line feature in PyQGIS QGIS 3.x

linepyqgis-3python 3qgis-3vector-layer

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

addLine1.jpg

How to Create a line with a fixed distance from a vector layer in python console.

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 .

Best Answer

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

Be careful!

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")

Related Question