4

I have one input point layer and out of that, I want to create an output LINE vector layer.

For each feature in my output line vector layer, I define a geometry which takes 2 point geometries. Figuratively speaking, imagine a line which connects both points -> this should be the line feature I want to add to my output layer!

I have tried it like this:

newEdge = QgsFeature(outFields)
geom = QgsGeometry.fromPolyline([geomFrom.asPoint(),geomTo.asPoint()]) # The error happens here!
newEdge.setGeometry(geom)

This had worked for me in QGIS2.x, but with QGIS3, I get the following error:

Traceback (most recent call last): File "", line 194, in processAlgorithm TypeError: index 0 has type 'QgsPointXY' but 'QgsPoint' is expected

Any suggestions?

1
  • 1
    you can try: QgsGeometry.fromPolyline([QgsPoint(geomFrom.asPoint()),QgsPoint(geomTo.asPoint())])
    – eurojam
    Dec 7, 2018 at 9:13

2 Answers 2

6

Try the following

points = []
pt = QgsPointXY(0,0)
points.append(pt)
pt = QgsPointXY(1,1)
points.append(pt) 
fields = some_layer.dataProvider().fields()
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPolylineXY(points))
feature.setFields(fields)
feature.setAttribute('id', 1)
some_layer.addFeature(feature)

I do not know the reason but pyqgis 3 works only with QgsPointXY and prefers creating polyline by QgsGeometry.fromPolylineXY(). I discovered this case when like you adapted some code from Qgis 2.18 - Python 2.7 to Qgis 3.2 - Python 3.6

2

Another approach using QgsPoint and QgsPolyline, a list of QgsPoints (standalone script using a memory layer but you should replace vl with the reference to your own layer)

vl = QgsVectorLayer("LineString", "temp", "memory")
pr = vl.dataProvider()

with edit(vl):
    pr.addAttributes([QgsField("id",  QVariant.Int)])
    vl.updateFields()
    points = []
    pt1 = QgsPoint(0,0)
    points.append(pt1)
    pt2 = QgsPoint(1,1)
    points.append(pt2) 
    fields = pr.fields()
    feature = QgsFeature()
    feature.setGeometry(QgsGeometry.fromPolyline(points))
    feature.setFields(fields)
    feature.setAttribute('id', 1)
    vl.addFeature(feature)

QgsProject.instance().addMapLayer(vl)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.