[GIS] Problem with encoding UTF-8 chars in Windows with PyQGIS

encodingpyqgispython

I have the problem to show characters (äöü) in a utf8 format in Windows. In Linux there is no problem and everything is displayed correctly. I use at the second line:

# -*- coding: utf-8 -*-

and further for importing and opening the shapefile:

base = os.path.basename(str(filename))
self.vlayer = QgsVectorLayer(filename, base, "ogr")

layer = self.vlayer
provider = layer.dataProvider()
layer.select(provider.attributeIndexes())
addA=[] 
for elem in layer:
    attrs_r = elem.attributeMap()
    for (k,attr) in attrs_r.iteritems():
        addA.append(attr.toString())

I also tried:

addA.append(u'%s'%attr.toString())

and

layer.setProviderEncoding(u'UTF-8')
layer.dataProvider().setEncoding(u'UTF-8')

But it has no effect and the characters are still not displayed correctly. Is there somehow a possibility to assign directly utf-8 to the shapefile?

Best Answer

I found the solution for the problem:

layer = self.vlayer
provider = layer.dataProvider()
layer.select(provider.attributeIndexes())
addA=[] 
for elem in layer:
    attrs_r = elem.attributeMap()
    for (k,attr) in attrs_r.iteritems():
        unicodestr = unicode(attr.toString(), "utf-8")
        addA.append(unicodestr)

Now it is possible to use for example the German "Umlaute"

Related Question