C++: Qt 5.3 fails to display UTF-8 character

2020-07-13 10:53发布

问题:

I am trying to display a unicode character (Euro sign) on a button using Qt and C++ in Visual Studio 2013. I tried the following code:

_rotateLeftButton->setText("\u20AC");

and

_rotateLeftButton->setText("€");

and

_rotateLeftButton->setText(QString::fromUtf8("\u20AC"));

and

_rotateLeftButton->setText(QString::fromUtf8("€"));

However, all of those lines result in the following:

All my code files are UTF-8 encoded, except for the moc files (.cxx). For whichever reason the moc executable does not generate them using unicode. Yet I was not able to get this unicode symbol displayed correctly. I also tried setting another font than the default one withouth success. Does anyone know what could be the problem?

Thank you for your help.

回答1:

QString::fromUtf8("€")

Will work if the file really is handled as UTF-8. As @n.m. commented, VS requires some help from a faux-BOM to ensure this.

QString::fromUtf8("\u20AC")

\u doesn't make sense in a byte string literal. You could spell it using \x byte escapes for the UTF-8 encoded version:

QString::fromUtf8("\xE2\x82\xAC")

Or use a wide string literal:

QString::fromWCharArray(L"\u20AC")