[Qgis-developer] Few improvements in PyQGIS

Martin Dobias wonder.sk at gmail.com
Thu Feb 4 16:24:19 EST 2010

Hi all

I hope this is a good news for developers using python. In svn trunk
(r12878) there are few additions that make QGIS API more pythonic.

QgsFeature allows direct access to attributes (get, set, delete attribute):
>>> f = QgsFeature()
>>> f[1] = QVariant("hello")
>>> print f[1].toString()
>>> del f[1]
>>> print f.attributeMap()

QgsVectorLayer and QgsVectorDataProvider support iterating (available
for those with sip >= 4.9).

layer.select([], QgsRectangle())
for f in layer:
  # do something with feature f

--- equals to ---

layer.select([], QgsRectangle())
f = QgsFeature()
while layer.nextFeature(f):
  # do something with feature f

That's it. The older idioms (using nextFeature) keep working too.

Inspired by a blog post from Sean Gillies:

Btw. fetching a list of values in an column gets this simple:
>>> lst = [ feat[1] for feat in layer ]
(just don't forget a select() call before iterating)

If you have any tips what other parts of QGIS API could be made more
pythonic, let me know.


More information about the Qgis-developer mailing list