[Qgis-user] Adding attributes to a layer with "memory" provider
Martin Dobias
wonder.sk at gmail.com
Mon Apr 19 06:53:08 PDT 2010
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 am not even able to add the attribute in the GUI using layer Properties
> dialog - the Type dropdown in Attributes - Add column window is empty. Is it
> bug or a feature that I cannot add attributes to memory layer?
That's the same problem you had with python code: there is missing a
list of native types.
Regards
Martin
More information about the Qgis-user
mailing list