Thursday, 7 May 2015

How to define the number of decimals when adding a new field as double to an attribute table with python in Qgis 2.1?


How to change the expression in order to define the number of decimals?


layer.dataProvider().addAttributes([QgsField("fieldname",  QVariant.Double)])


As I read in QGIS API Documentation:


Parameters
name Field name
type Field variant type, currently supported: String / Int / Double
typeName Field type (eg. char, varchar, text, int, serial, double).

len Field length
prec Field precision


So I try:


layer.dataProvider().addAttributes([QgsField("fieldname",  QVariant.Double, 10, 3)])

But I get this error:


TypeError: arguments did not match any overloaded call:

QgsField(QString name=QString(), Type type=QVariant.Invalid, QString
typeName=QString(), int len=0, int prec=0, QString comment=QString()):
argument 3 has unexpected type 'int'


QgsField(QgsField): argument 1 has unexpected type 'str'

Answer



Try:


layer.dataProvider().addAttributes([QgsField("fieldname",  QVariant.Double, "double", 10, 3)])

This is the correction that suggests the error message.


I used it in my system for adding two fields (area and perimeter) in the attributes table of my shapefile and it works.


My snipped code


.
.

.
fields = [ QgsField('area', QVariant.Double, 'double', 20, 2),
QgsField('perimeter', QVariant.Double, 'double', 10, 3) ]
.
.
.

The attributes table of my shapefile:


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...