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()?

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
xx77aBs
  • 4,678
  • 9
  • 53
  • 77

3 Answers3

29

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

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
  • Huh, feeling stupid right now :D I didn't know that it exists ;) Thanks :) – xx77aBs Jan 02 '12 at 22:18
  • 2
    Don't suppose something like this can be done for qt5? Seems setCodecForCStrings has been removed... – hanetzer Aug 07 '14 at 03:18
  • 2
    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++)? – Samuel Harmer Sep 24 '14 at 12:18
3

setCodecForCStrings() had been deprecated. Try instead,

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

It worked for me.

Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
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.

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
Peter Gulutzan
  • 465
  • 2
  • 8