[Qgis-user] Adding attributes to a layer with "memory" provider

Martin Dobias wonder.sk at gmail.com
Tue Apr 20 06:15:50 PDT 2010


2010/4/19 Václav Řehák <rehakv01 at gmail.com>:
>> [...]
>> You can add attributes using this code:
>>
>> pr = self.lines.dataProvider()
>>
>> # add fields - to preserve correct order they must be added one-by-one
>> (d'oh)
>> pr.addAttributes( { "name" : "string" } )
>> [...]
>
> I have tried your suggestion, but it also doesn't work for me:
>
> self.lines = QgsVectorLayer("LineString", "temporary_lines", "memory")
> pr = self.lines.dataProvider()
> self.lines.startEditing()
> added = pr.addAttributes( { "label" : "string" } )
> QgsMapLayerRegistry.instance().addMapLayer(self.lines)
> self.lines.commitChanges()

Ouch, sorry I was wrong, I've mistakenly pasted an invalid snippet.
This is how to do it:

lines = QgsVectorLayer("LineString", "temporary_lines", "memory")
pr = lines.dataProvider()
ret = pr.addAttributes( [ QgsField("label", QVariant.String) ] )
QgsMapLayerRegistry.instance().addMapLayer(lines)

(can be used from python console, too)

Regards
Martin



More information about the Qgis-user mailing list