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]

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

| improve this answer | |
layer = iface.activeLayer()
intfields = [f for f in layer.fields() if f.typeName().startswith('Int')]

Found typeName here

| improve this answer | |
  • 1
    Thanks that was very helpful! Sorry, finally I accepted Kadir's answer because it works even slightly better for me. – DGIS Mar 14 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.