7

I have to set the character encoding for all layers from system to UTF-8.

Is there a way to change this in all loaded layers at once?

I'm using QGIS 2.8.1 on Windows 7.

1 Answer 1

13

You can use the following, which should set the encoding of your loaded layers to UTF-8:

PyQGIS 3:

for layer in QgsProject.instance().mapLayers().values():
    layer.setProviderEncoding(u'UTF-8')
    layer.dataProvider().setEncoding(u'UTF-8')
    print (layer.name(), layer.dataProvider().encoding())

PyQGIS 2:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    layer.setProviderEncoding(u'UTF-8')
    layer.dataProvider().setEncoding(u'UTF-8')
    print layer.name(), layer.dataProvider().encoding()   #Optional check: prints layer name and its encoding source

Remember to save your project file (.qgs) afterwards.

As suggested by @meles, you can input the above code into the Python Console (Plugins > Python Console; Extensions > Python Console; (Ctrl+Alt+T)).

5
  • 1
    That did the trick. Maybe you could mention in your answer that you have to insert the commands in Extension->Python console (Ctrl + Alt + P). That might help other people comming by. Thank you for your help.
    – meles
    Commented Jun 29, 2015 at 10:00
  • @meles - Awesome buddy and your most welcome, glad you got it working! I've edited the post thanks to your suggestion =)
    – Joseph
    Commented Jun 29, 2015 at 10:06
  • @Joseph thanks for sharing what is the difference b.w setProviderEncoding and dataProvider().setEncoding(u'UTF-8') Commented Nov 25, 2016 at 12:17
  • 2
    @MohammadFaizanKhan - Good question! From the API, setProviderEncoding() sets the text encoding of the data provider; dataProvider().setEncoding() sets the encoding used for accessing data from layer. As this was more than a year ago, my guess is they were both required for the data to be encoded and for QGIS to read the encoded data but I can't remember!
    – Joseph
    Commented Nov 25, 2016 at 12:31
  • @Mohammad and others, setProviderEncoding does exactly dataProvider.setEncoding. So no need to use both.
    – BlackTesta
    Commented Aug 20 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.