PDA

View Full Version : QString::fromUtf8 problems converting micro sign



smacchia
8th February 2011, 22:09
I am trying to convert the unicode micro-sign to use in a QString. I have tried the following:


QByteArray b(1, 0xb5);
QString s = QString::fromUtf8(b.constData(), b.length());

But the string isn't the micro-sign but a question mark in a circle.
I also tried:


QChar c(181);
QString s(c);

With the same result.
When using this with PyQt:


b = QByteArray(1, "\xb5")
s = QString.fromUtf8(b.data(), b.length())

or


c = QChar(181);
s = QString(c);

both c and b when I print them are also the question mark in the circle. When I try to convert to a QString I get the following error from the python interpreter:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xb5' in position 0:ordinal not in range(128)
I have tried a variety of combinations and googled everywhere for an adequate solution, to no avail.

FWIW, the python string conversion works as I'd expect, but I need a QString:

>> s = unichr(181).encode("utf8")
>> print s
>> µ
>> print QString(s)
Traceback (most recent call last):
File "<input>", line 2, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
Any help with this is greatly appreciated.

wysota
10th February 2011, 00:00
0xb5 is very unlikely to be a micro. The best thing you can do is to just put the real micro character in the file and save it with utf-8 encoding. Also make sure your font contains a micro character at this position.

ChrisW67
10th February 2011, 01:04
The Unicode code point for the "Micro sign" is \u00b5. In UTF-8 encoding this is a two byte sequence \xc2\xb5. You could also use Greek small letter mu \u03bc.

Any of these:


QString s(QChar(0x00b5));
QString s = QString::fromStdWString(L"\u00b5");
QString s = QString::fromUtf8("\xc2\xb5");


This works for me but I am not sure if it is by-design or by-accident:


QString s = QString::fromUtf8("\u00b5");


Look up Unicode code points here: http://www.unicode.org/charts
Convert into a bucket of other forms here: http://people.w3.org/rishida/tools/conversion/

smacchia
15th February 2011, 23:07
Thanks! This is a big help.