Reputation: 9455
My app uses "μ" symbol in a label, in Qt4 it displays fine but in Qt 5 it doesn't for the same code. I am using following two lines at two different places where it works fine in Qt4 :
QChar('μ').toLatin1()
QString::fromUtf8(rateText.toLatin1()));
In second case the string contains the "μ" symbol.
In my main main.cpp, I have added following code:
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#else
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
#endif
Edit:
This line is enough in Qt 5 as Qt 5 uses utf-8 as default
ui->timeLabel->setText("Time = "+rateText); //rateText contains 'μ' symbol
But it doesn't work in Qt4, even this does not work
ui->timeLabel->setText("Time = "+rateText.toUtf8());
Only this worked for me:
ui->timeLabel->setText("Time = "+QString::fromUtf8(rateText.toLatin1()));
And I need a single solution which works across
Upvotes: 2
Views: 6027
Reputation: 25155
QString::fromUtf8(rateText.toLatin1()));
This doesn't make sense: you convert a string to latin1, just to the interpret the latin1 string as UTF8. You shouldn't do such conversions at all unless you explicitly need a QByteArray/const char*.
toLatin1()
will convert the micro sign to 0xb5
, while the micro sign in UTF-8 would be 0xc2b5
.
So instead of
QString foo = QString::fromUtf8(rateText.toLatin1()));
just do
QString foo = rateText;
If you need to convert to byte array, make sure you convert back from the same encoding you converted to.
QByteArray ba = rateText.toUtf8();
... do stuff with ba
QString s = QString::fromUtf8(ba);
There should be only few occasions where this is needed though.
To track down encoding errors, I suggest to disable any implicit const char*/QByteArray <-> QString conversions via
DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII
Upvotes: 3