Set Qt default encoding to UTF-8

爷,独闯天下 提交于 2019-11-29 11:34:20

问题


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


回答1:


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




回答2:


setCodecForCStrings() had been deprecated. Try instead,

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

It worked for me.




回答3:


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.



来源:https://stackoverflow.com/questions/8705488/set-qt-default-encoding-to-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!