[Qgis-developer] Issue with creating new feature

Nathan Woodrow madmanwoo at gmail.com
Wed Feb 27 03:40:08 PST 2013


Alex,

You can also set the field using this syntax:

f = QgsFeature()
f['id'] = 0
f[0] = 0

That has worked for me in the past unless something has changed since I
tested it last.

- Nathan


On Wed, Feb 27, 2013 at 9:06 PM, Alexander Bruy <alexander.bruy at gmail.com>wrote:

> Hi all,
>
> during plugin update to new vector API I found some strange
> behaviour with creating new features in vector layer/file writer.
> There is nice description about how to retrieve features and
> attributes from existing vector layer, but I can't find any
> information about creating new ones.
>
> Here is my test code for Python console:
>
> >>>from PyQt4.QtCore import *
> >>>fields = QgsFields()
> >>>fields.append(QgsField("id", QVariant.Int, "", 20))
> >>>fields.append(QgsField("value", QVariant.String, "", 255))
> >>>fields.append(QgsField("area", QVariant.Double, "", 20, 6))
> >>>fields.append(QgsField("perim", QVariant.Double, "", 20, 6))
> >>>w = QgsVectorFileWriter("/home/alex/test.shp", "utf-8", fields,
> >>>QGis.WKBPolygon, None)
> >>>f = QgsFeature()
> >>>f.setAttribute("id", QVariant(0))
> False
> >>>f.setAttribute(0, QVariant(0))
> False
>
> It is impossible to add attribute by its name or index. In API docs
> I found method setFields() that used to "assign a field map with
> the feature to allow attribute access by attribute name". But when
> I assign field map to feature
>
> >>>f.setFields(fields)
>
> and try to add attribute again by name or id I get crash
> (stacktrace attached).
>
> It is possible to set all attributes at once using
>
> >>>f.setAttributes([QVariant(0), QVariant("text"), QVariant(2.3),
> QVariant(100.456)])
>
> Is this correct or maybe I miss something?
>
> Thanks
> --
> Alexander Bruy
>
> _______________________________________________
> Qgis-developer mailing list
> Qgis-developer at lists.osgeo.org
> http://lists.osgeo.org/mailman/listinfo/qgis-developer
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20130227/b5348058/attachment.html>


More information about the Qgis-developer mailing list