laurent
laurent

Reputation: 90766

Displaying UTF-8 characters in a PlainTextEdit

I'm trying to display Chinese characters encoded in UTF-8 in a PlainTextEdit control, but it doesn't render them properly.

My data comes from a database and I know that the string I get in Qt is correct (the bytes are the same as in the database). Once I have the Chinese character in a QString, I tried various things to display it but always results in either question marks or random ASCII characters:

QString chineseChar = query.value(fieldNo).toString(); // get the character

ui->plainTextEdit->appendPlainText(chineseChar); // doesn't work
ui->plainTextEdit->appendPlainText(chineseChar.toUtf8()); // doesn't work
ui->plainTextEdit->appendPlainText(QString::fromUtf8(chineseChar.toAscii()); // doesn't work

Any suggestion on how to handle that?

Upvotes: 1

Views: 2832

Answers (1)

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

"My data comes from a database and I know that the string I get in Qt is correct (the bytes are the same as in the database)."

How did you check that? Try with chineseChar.toUtf8().toHex().

Once your string data is in a QString, all UI elements accepting a QString will handle it correctly. Usually the error happens when converting from plain text data(const char*/QByteArray) to the QString. The conversions here:

ui->plainTextEdit->appendPlainText(chineseChar.toUtf8()); // doesn't work
ui->plainTextEdit->appendPlainText(QString::fromUtf8(chineseChar.toAscii()); // doesn't work

convert the unicode string to a bytearray, and then implicitely back to a QString, as those methods expect a QString. I suggest you define QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to avoid any unwanted QByteArray<->QString conversions.

If the string is wrong, the error usually happened before, when converting from QByteArray/const char* to QString, i.e. in query.value(fieldNo).toString(). Try with:

 QString chineseChar = QString::fromUtf8( query.value(fieldNo).toByteArray() ); 

If that doesn't help, the problem is somewhere in QtSQL assuming the wrong encoding for the data it receives from the database.

Upvotes: 1

Related Questions