13

I am trying to change an plugin from QGIS 1.8 to 2.0. In the 1.8 version I create a table of the field names like this:

layer = vlayer
provider = layer.dataProvider()
feat = QGSFeatrue()
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
fieldNames = []

while provider.nextFeature(feat)
    fields = layer.pendingFields()
    for (k, field) in fields.iteritems():
         fieldNames.append(field.name())

I tried this for the 2.0 version with

layer = vlayer
fieldNames = []

for feature in layer.getFeatures():
    fields = layer.pendingFields()
    for (k, field) in fields.iteritems():
         fieldNames.append(field.name())

But pendingFields() does not work for me. Is there now a new method to get the names of the fields?

24

It is simpler than with version 1.8:

layer = qgis.utils.iface.activeLayer()  
fields = layer.pendingFields()   
field_names = [field.name() for field in fields]

or in one line

field_names = [field.name() for field in layer.pendingFields() ]

an after

for elem in layer.getFeatures():  
   print dict(zip(field_names, elem.attributes()))
{u'adip': 17, u'dipdir': 130, u'tdip': 29}
{u'adip': 55, u'dipdir': 325, u'tdip': 75}
.....

Generally to explore a new function, I use the dir() or the see module to examine what's inside:

dir(fields)
['FieldOrigin', 'OriginEdit', 'OriginJoin', 'OriginProvider', 'OriginUnknown', '__class__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'at', 'clear', 'count', 'extend', 'field', 'fieldOrigin', 'fieldOriginIndex', 'indexFromName', 'isEmpty', 'remove', 'size', 'toList']

or

see(fields)
[]                 hash()             help()             len()
repr()             str()              .FieldOrigin()     .OriginEdit
.OriginJoin        .OriginProvider    .OriginUnknown     .append()
.at()              .clear()           .count()           .extend()
.field()           .fieldOrigin()     .fieldOriginIndex()
.indexFromName()   .isEmpty()         .remove()          .size()
.toList()

And you can see that there is a field() function so

print fields.field(0)
qgis.core.QgsField object at 0x163E39C0

and a field has a name, a type, a precision,...:

see(fields.field(0))
<                 <=                ==                !=                >
>=                hash()            help()            repr()
str()             .comment()        .displayString()  .length()
.name()           .precision()      .setComment()     .setLength()
.setName()        .setPrecision()   .setType()        .setTypeName()
.type()           .typeName()

so:

fields.field(0).name()
u'adip'
fields.field(0).type()
2
fields.field(0).typeName()
u'Integer'
fields.field(0).precision()
0
....

with .dataProvider()

It is .field()

....
prov = layer.dataProvider()
prov.fields().field(0).name()
u'adip'
prov.fields().field(0).typeName()
u'Integer'

and

field_names = [field.name() for field in prov.fields()]
  • ok this workes, but only in the Python Editor of qgis. When I use this function in my plugin nothing happens. The function is going untill for field in fields but there it stops. I tried to show a messagebox afterwards but it does not reach the codeline. Maybe I forgot to import something? I have qgis.core, qgis.gui and qgis.utils imported. – Martin Nov 4 '13 at 15:49
  • you must use .dataprovider(), see addition in my reply – gene Nov 4 '13 at 17:32
  • Thank you. It is working. The problem was that I try to get the layer id from the active layer with getLayerID() but this is not working anymore. – Martin Nov 7 '13 at 16:25
2

It works for instance like this (since the last QGIS dev 1.9):

layer = vlayer # QGsVectorlayerObject
prov = vlayer.dataProvider()
fieldNames = []
fields = prov.fields()
for field in fields:
    fieldNames.append( field.name() )
  • 1
    For me this does not work. When i try to iterate through fields nothing happens. Is the dataProvider in 2.0 still usable? – Martin Nov 4 '13 at 11:22
  • 1
    jup it is. And for my plugin the above code works without problems. try to print out the type and content of the objects while executing the code. Helps debugging – Curlew Nov 4 '13 at 11:31
  • worked with QgsMapLayerRegistry.instance().mapLayers().values(): – Muhammad Faizan Khan Nov 29 '16 at 10:20

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.