TransWikia.com

Accessing attribute data type in PyQGIS

Geographic Information Systems Asked by kyuss on January 4, 2021

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?

3 Answers

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: <qgis.core.QgsField object at 0x46d9d40>, 
1: <qgis.core.QgsField object at 0x46d9b00>, 
2: <qgis.core.QgsField object at 0x46d9cb0>, 
3: <qgis.core.QgsField object at 0x46d9ef0>, 
4: <qgis.core.QgsField object at 0x46d9dd0>}

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

Correct answer by Nathan W on January 4, 2021

It's not necessary to write your own plugin for this purpose, you can use your own customised edit user interface. See also these blog posts:

https://woostuff.wordpress.com/2011/09/05/qgis-tips-custom-feature-forms-with-python-logic/

and

http://linfiniti.com/2009/11/creating-dynamic-forms-a-new-feature-headed-for-qgis-1-4/

Answered by webrian on January 4, 2021

For QGIS 3 users:

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

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

Answered by natsuapo on January 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP