Set Qt default encoding to UTF-8
Asked Answered
H

3

16

In my Qt application my source code files are encoded as UTF-8. For the following code...

QMessageBox::critical(this, "Nepoznata pogreška", "Dogodila se nepoznata pogreška! Želite li zatvoriti ovaj program ?", QMessageBox::Yes, QMessageBox::No);

...when I show that message box, the character "š" wouldn't be displayed as "š", but as something strange. This is because Qt converts all C-strings as if they are encoded using LATIN-1. To solve this I've been using:

QMessageBox::critical(this, QString::fromUtf8("Nepoznata pogreška"), QString::fromUtf8("Dogodila se nepoznata pogreška! Želite li zatvoriti ovaj program ?"), QMessageBox::Yes, QMessageBox::No);

Is there a way to get rid of all the calls to QString::fromUtf8()?

Horsemint answered 2/1, 2012 at 21:24 Comment(1)
P
29

Have you tried using QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"))?

Poleyn answered 2/1, 2012 at 21:55 Comment(3)
Huh, feeling stupid right now :D I didn't know that it exists ;) Thanks :)Horsemint
Don't suppose something like this can be done for qt5? Seems setCodecForCStrings has been removed...Rearward
I'm afraid I can't answer for sure as I'm not working on anything which uses Qt anymore. My guess would be that Qt5 assumes all source files are UTF-8 encoded (rather than Latin-1) which would explain why they removed this. If you're having a similar problem to this then all I would just is to check all your source files are UTF-8 encoded using your favourite programmer's text editor (e.g. Notepad++)?Poleyn
C
3

setCodecForCStrings() had been deprecated. Try instead,

QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

It worked for me.

Consubstantiate answered 19/4, 2018 at 11:46 Comment(0)
R
0

Regarding the "guess" that "Qt5 assumes all source files are UTF-8 encoded": Thiago Macieira explains the decision made by Qt's developers here.

The assumption can be disabled with QT_NO_CAST_FROM_ASCII according to the documentation.

Rilda answered 30/5, 2016 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.