PyQGIS Attribute Table – Accessing Attribute Data Types

fields-attributespyqgis

I've been developing a Plugin on QGIS platform using PyQGIS. So far plugin does the following: You can select any feature of the already loaded vector layer in QGIS. After selection, plugin displays attribute names, and associated attribute values, explicitly for the selected feature. You can change those values, and save them.

Now I would like to add a possibility to define data type for every attribute that loaded layer contains. For example, I would like that first attribute named, let's say, ''road_id'' can only be 4-digit long integer, so if you enter string value or even a 5-digit integer, it gets rejected.

Is it possible to do that? If it is, which are the classes/methods I should be looking into?

Best Answer

For QGIS 3 users:

The function pendingFields() has been replaced by fields()

for field in layer.fields():
    print( "Name:%s, TypeName:%s, Type:%s, Length:%s" % ( field.name(), field.typeName(), field.type(), field.length()))