Unicode in QML/C++ issue

删除回忆录丶 提交于 2021-01-28 07:31:55

问题


In QML I have a TextArea. When I set the text property of this TextArea to "ÆØÅ" it shows "ÆØÅ" when the program runs.

I also get text through some functions that I want to show in the same TextArea, but then "ÆØÅ" is shown as "???".

The strings come from this C++ function:

QString Tts::morseToChar(QString morse)
{
    if(morse == ".-")               return "A";
    else if (morse == "-...")       return "B";
    ...
    ...
    else if (morse == ".-.-")       return "Æ";
    else if (morse == "---.")       return "Ø";
    else if (morse == ".--.-")      return "Å";
}

The return string gets added to a QML string:

property string ttsChar: ""
ttsChar += ttsSpeak.morseToChar(morse)
_ttsTextArea.text += ttsChar

All files are saved as UTF-8.

What conversion am I missing to get this to work?


回答1:


Try returning the universal character name instead of the utf-8 representation.

QString Tts::morseToChar(QString morse)
{
    if(morse == ".-")               return "A";
    else if (morse == "-...")       return "B";
    ...
    ...
    else if (morse == ".-.-")       return u8"\u00C6";
    else if (morse == "---.")       return u8"\u00D8";
    else if (morse == ".--.-")      return u8"\u00C5";
}

You can search for universal character names here which is where the names for Æ (\00C6), Ø (\00D8) and Å (\00C5) were found.

See this answer for more information on why the utf-8 representation isn't allowed in c++ source files.




回答2:


The default constructor for QStrings from char * uses the fromAscii() function.

Chances are your strings are actually encoded in UTF-8, so there's two things to try:-

a : Return wide chars:

return L"Æ";

b: Or, explicitly convert from UTF8

 return QString::fromUtf8("Æ");


来源:https://stackoverflow.com/questions/20330665/unicode-in-qml-c-issue

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