8

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'
6

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

  • thanks it works fine!! so I suppose I do the same for integers as QVariant.Double, "integer", 10 and strings as QVariant.String, "string", 5 ? – Eleftheria Dec 26 '15 at 8:50
  • Integers would be QVariant.Int. For example: QgsField('ID', QVariant.Int, len=4) – BritishSteel Jan 4 '16 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.