[QGIS-Developer] error adding new feature to empy layer

Richard Duivenvoorde rdmailings at duif.net
Thu Apr 4 01:11:36 PDT 2024


Hi Pierluigi,

Are you sure the creation of the geometry is ok?

Because your code with some hardcoded values in it, just works in my python console:


vl = QgsVectorLayer("LineString", "braiding_river", "memory")
pr = vl.dataProvider()
# add fields
pr.addAttributes([
     QgsField("reach", QVariant.String),
     QgsField("braiding", QVariant.Double),
     QgsField("Length", QVariant.Double)])
vl.updateFields()
print(f"{vl.isValid()=}")
feat_list=[]

fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromWkt('LINESTRING (30 10, 10 30, 40 40)'))
fet.setAttributes([ 'test',  2,  2])
print(f"{fet.isValid()=}")
feat_list.append(fet)

(result, newFeatures) = pr.addFeatures(feat_list)

print(f"{result=}")
print(newFeatures)



Regards,

Richard Duivenvoorde



On 4/4/24 9:58 AM, pierluigi de rosa via QGIS-Developer wrote:
> vl = QgsVectorLayer("LineString", "braiding_river", "memory")
> vl.setCrs(crs)
> pr = vl.dataProvider()
> # add fields
> pr.addAttributes([
>      QgsField("reach", QVariant.String),
>                    QgsField("braiding", QVariant.Double),
>                    QgsField("Length", QVariant.Double)])
> vl.updateFields()
> feat_list=[]
> 
> then I populate the layer where inside a for cycle I have
> 
> fet = QgsFeature()
> fet.setGeometry(QgsGeometry.fromPolylineXY(reach)) #reach is a list of
> QgsPointXY
> fet.setAttributes([ str(breakval),  brIndex,  lenReach])
> feat_list.append(fet)
> 
> Outside for cycle I do:
> 
> (result, newFeatures) = pr.addFeatures(feat_list)
> 
> But I have always result to False so the feature is not added.



More information about the QGIS-Developer mailing list