With the following line of code, I get a list of field names for the layer layer.

 fields = layer.fields().names()

However, I would like to get only those fields with the datatype Integer. How would I do that? I checked the class QgsFields but I don't see a function that relates to the datatype. Is there a way to do that?


By type name (typeName()):

int_types = ["Integer", "Integer64"]
int_fields = [field for field in iface.activeLayer().fields() if field.typeName() in int_types]

OR by type number (type()):

int_types = [2, 4] # 2: Integer, 4: Integer64
int_fields = [field for field in iface.activeLayer().fields() if field.type() in int_types]

Type of some fields may be Integer64. Integer64 equals QVariant.LongLong actually, but it could be considered as integer.

  • Do you know where I find which field.types() are which, without using field.typeName()? – BERA Oct 22 '20 at 16:16
  • @BERA "Field types vary depending on the data source. Examples are char, int, double, blob, geometry, etc" (from Docs). I found QVariant Types. And some types which are, I guess, probably available for spatial data formats. – Kadir Şahbaz Oct 23 '20 at 0:50
  • 1
    @BERA (Type name -> Type number)... bool -> 1... integer, int2(16bit), int4(32bit) -> 2... int8(64bit) -> 4... double, numeric, decimal, real, double precision -> 6... string, text -> 10... date -> 14... time -> 15... datetime -> 16... Add temporary sctrach layer and try to add a new field. You will see a lot of different types of field. – Kadir Şahbaz Oct 23 '20 at 1:04
  • Ok! Im lookning for a way in pyqgis to do what in arcgis would be: [f for f in arcpy.ListField(feature_class) if f.type == 'String'] or list only numeric field etc. And not have to worry about Int/Int64/Int32 etc. or String/varchar/??? etc. There seems to be so many different field types in pyqgis – BERA Oct 23 '20 at 5:58
layer = iface.activeLayer()
intfields = [f for f in layer.fields() if f.typeName().startswith('Int')]

Found typeName here

  • 1
    Thanks that was very helpful! Sorry, finally I accepted Kadir's answer because it works even slightly better for me. – DGIS Mar 14 '20 at 19:44

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.