[Qgis-developer] iterating over fields an values API 2.0

PIERRE Sylvain sylvain.pierre at cg67.fr
Tue Feb 18 06:53:03 PST 2014



Yes!
That's it

Thanks

PS: Don't you think it should be clearly documented in the pyqgis cookbook?


-----Message d'origine-----
De : Martin Dobias [mailto:wonder.sk at gmail.com] 
Envoyé : lundi 17 février 2014 18:43
À : PIERRE Sylvain
Cc : qgis-developer at lists.osgeo.org
Objet : Re: [Qgis-developer] iterating over fields an values API 2.0

On Mon, Feb 17, 2014 at 10:36 PM, PIERRE Sylvain <sylvain.pierre at cg67.fr> wrote:
>
>
> When iterating over vector features like this:
>
> fields = layer.pendingFields()
>   field_names = [field.name() for field in fields]
>   for elem in layer.getFeatures():
>           atr = dict(zip(field_names, elem.attributes()))
>
> returns this:
>
> {PyQt4.QtCore.QString(u'off_set'): <PyQt4.QtCore.QVariant object at
> 0x05115C70>, PyQt4.QtCore.QString(u'code'): <PyQt4.QtCore.QVariant 
> 0x05115C70>object at
> 0x05115BC8>, PyQt4.QtCore.QString(u'pk'): <PyQt4.QtCore.QVariant 
> 0x05115BC8>object at
> 0x05115C00>, PyQt4.QtCore.QString(u'id'): <PyQt4.QtCore.QVariant 
> 0x05115C00>object at
> 0x05115B90>, PyQt4.QtCore.QString(u'annee'): <PyQt4.QtCore.QVariant 
> 0x05115B90>object
> at 0x05115CA8>, PyQt4.QtCore.QString(u'id_anom'): 
> <PyQt4.QtCore.QVariant object at 0x05115B58>, PyQt4.QtCore.QString(u'fk_position'):
> <PyQt4.QtCore.QVariant object at 0x05115C38>,
> PyQt4.QtCore.QString(u'resolu'): <PyQt4.QtCore.QVariant object at
> 0x05115CE0>}
>
> Instead of tupple like u'off_set': 1 ...

You have not set SIP api to version 2 to QString, QVariant and other Qt classes. QGIS python package tries to do that automatically for you, but if you imported PyQt4 python modules before QGIS python modules, that will not work. You have two options:
1. move import of QGIS module before PyQt4 2. keep the order of imports as is, but put these lines before import of PyQt4:
import sip
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)


This is only necessary in standalone applications - inside QGIS application this initialization is done before any plugins are loaded, so this issue does not come up. Probably in qgis __init__.py there should be some code checking if there are not Qt classes imported with API v1 - in such case we could throw an exception.

Regards
Martin


More information about the Qgis-developer mailing list