2

I have two input vector layers and I want to create an Output vector layer by doing some calculations. But somehow, the setAttribute method does not work. In QGIS 2.18, I was able to set an attribute like this:

ID = 'id'

inEdges = self.parameterAsSource(parameters, self.INPUT_VECTOR_LAYER_EDGES, 
                                          context)

# get field indices for inputlayer
fieldsEdges= inEdges.fields()

idxEdgeId = fieldsEdges.indexFromName(ID)

edgeIdTrimmed = some calculation ...
(...)
newEdge = QgsFeature()    
newEdge.setAttribute(idxEdgeId, edgeIdTrimmed)   # <-- the error is here

But now, using QGIS 3, I get the following error message:

Traceback (most recent call last): File "", line 125, in processAlgorithm KeyError: '0'

Any ideas on how to set an attribute value in QGIS 3?

Is there any other method to do this now?

And what does that KeyError mean exactly?

  • Like this?: idxEdgeId = fieldsEdges.indexFromName('edgeid'); newEdge.setAttribute(idxEdgeId, edgeIdTrimmed) – applebrown Nov 29 '18 at 9:27
  • @BERA I edited my question, please have a look – applebrown Nov 29 '18 at 9:37
3

Your error means that your newEdge object (a newly created QgsFeature) doesn't have attribute at key 0.

When you do newEdge = QgsFeature(), you create a new feature instance but this instance doesn't have any fields.

You first need to add your fields to the feature before trying to assign some values to them

newEdge. = QgsFeature()
newEdge.setFields(inEdges.fields())
newEdge.setAttribute(idxEdgeId, edgeIdTrimmed)

Alternatively, you can use this syntax:

newEdge[idxEdgeId] = edgeIdTrimmed

Or even more concise:

newEdge[ID] = edgeIdTrimmed
  • 1
    Glad to help you :) – YoLecomte Nov 29 '18 at 10:06
  • May I ask you how to add a field to the QgsFeature? (In addition to the line newEdge.setFields(inEdges.fields()) – applebrown Nov 29 '18 at 10:29
  • Please ask another question for this issue with more information about what you're trying to do. Note that if you want to save a feature in a layer, the fields of both must be consistent. – YoLecomte Nov 29 '18 at 10:43

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.