Thursday 24 November 2016

Accessing attribute data type in PyQGIS?


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?



Answer



If you need to get the fields of a layer you can use QgsVectorLayer::pendingFields() in Python like so:


fields = layer.pendingFields()

which will give you something like this:


{0: , 
1: ,
2: ,

3: ,
4: }

Which you can then go though get the name, data type, and length:


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

Name:Seg_Par Type:String, Length:10
Name:Lot_num Type:String, Length:5
Name:Plan_num Type:String, Length:10

Name:Tenure Type:String, Length:2
Name:Area_ha Type:Real, Length:14

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...