[Qgis-developer] how to add a new field to an existing layer?

Ricardo Filipe Soares Garcia da ricardo.garcia.silva at gmail.com
Tue Aug 10 19:49:05 EDT 2010


Hi Martin, list

I did as you recommended, but now I'm getting the following error:

Traceback (most recent call last):
  File "/home/ricardo/.qgis/python/plugins/ChannelFromPoints/ChannelFromPointsDialog.py",
line 41, in accept
    self.callbackFunction(pLayer, params)
  File "/home/ricardo/.qgis/python/plugins/ChannelFromPoints/ChannelFromPoints.py",
line 119, in calculate_channel
    provider.ChangeAttributeValues(values)
TypeError: 'Capability' object is not callable

My revised code:


provider = pointLayer.dataProvider()
newField = QgsField("channel", QVariant.Double)
provider.addAttributes([newField])
newFieldIndex = provider.fieldNameIndex(newField.name())
#more code
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
feat = QgsFeature()
while provider.nextFeature(feat):
    # more code, calculating the value of the 'channelValue' variable
    values = {feat.id() : {newFieldIndex: QVariant(channel)}}
    provider.ChangeAttributeValues(values)


Do you have some insight on this error? Thanks for you help

On Tue, Aug 10, 2010 at 9:55 PM, Martin Dobias <wonder.sk at gmail.com> wrote:
> Hi Ricardo
>
> On Mon, Aug 9, 2010 at 2:50 PM, Ricardo Filipe Soares Garcia da
> <ricardo.garcia.silva at gmail.com> wrote:
>> Hello list
>>
>> How can I add a new field to an existing layer and insert some new
>> values in it? In the following example, pointLayer refers to an
>> existing layer, previously created using the memory provider. This
>> code is creating the new field, but I cannot insert the values in it.
>> Although it runs without any error, when I look at the layer's
>> attribute table, the new field is there, but every feature has it as
>> NULL.
>
> The problem is that in your code you only modify a local copy of the
> data - your change is not propagated to the provider. To actually
> modify the data, use something like this:
>
> values = { fid : { attr_1 : QVariant(value_1), attr_2 :
> QVariant(value_2) }, ... }
> provider.changeAttributeValues( values )
>
> You pass the provider a dictionary where keys are feature IDs, values
> are dictionaries of changed attributes (key = attribute index, value =
> new attribute value).
>
>> By the way, I think this kind of operation would be a nice thing
>> to go into the pyqgis cookbook
>
> Sure, it just needs some time :-)
>
> Regards
> Martin
>



-- 
___________________________ ___ __
Ricardo Garcia Silva


More information about the Qgis-developer mailing list