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

Václav Řehák rehakv01 at gmail.com
Mon Apr 19 09:49:56 PDT 2010


Hi Marting

Dne 19. dubna 2010 15:53 Martin Dobias <wonder.sk at gmail.com> napsal(a):

> Hi Vaclav,
>
> 2010/4/19 Václav Řehák <rehakv01 at gmail.com>:
> > Hi,
> >
> > in my plugin I create a layer using the following code:
> >
> > self.lines = QgsVectorLayer("LineString", "temporary_lines", "memory")
> > self.lines.startEditing()
> > field = QgsField("label", QVariant.String)
> > field.setLength(100)
> > ret = self.lines.addAttribute(field)
> > QgsMapLayerRegistry.instance().addMapLayer(self.lines)
> > self.lines.commitChanges()
> >
> > However, the field is not added to the layer and "ret" is false. I
> realized
>
> 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" } )
> pr.addAttributes( { "age" : "int" } )
> pr.addAttributes( { "size" : "double" } )
>
> Your approach should ideally work too, but as I'm looking into the
> code, there are some missing bits that prevent your code to work as
> well. I'll fix it, but the solution I've posted above will work with
> older qgis releases, too.
>

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()

I don't see "label" in attributes table of my layer and "added" has value
False.

Thanks,

Vaclav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20100419/63c3e564/attachment.html>


More information about the Qgis-user mailing list