I am reading an html file. The file basically contains Unicode texts as follows:
<b>akko- sati (ā + kruś), akkhāti (ā + khyā), abbahati (ā + bṛh)</b>
But the QTextBrowser is not interpreting the Unicode fonts. So the QTextBrowser shows them as follows:
akko- sati (Ä + kruÅ›), akkhÄti (Ä + khyÄ), abbahati (Ä + bá¹›h)
The QTextBrowser is correctly interpreting the html tags. But what’s wrong with the Unicode fonts?
Following are my codes for reading and populating the Unicode contents:
void MainWindow::populateTextBrowser(const QModelIndex &index)
{
QFile file("Data\\" + index.data().toString() + ".html");
if (!file.open(QFile::ReadOnly | QFile::Text)) {
statusBar()->showMessage("Cannot open file: " + file.fileName());
}
QTextStream textStream1(&file);
QString string = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><link rel='stylesheet' type='text/css' href='Data/Accessories/qss.css' />";
string += textStream1.readAll();
ui->textBrowser->setHtml(string);
}
However, if I do not read the Unicode content from an html file but directly type them into the parameter, then only it interprets the Unicode fonts. For example, if I do as follows it is fine:
ui->textBrowser->setHtml("<b>akko- sati (ā + kruś), akkhāti (ā + khyā), abbahati (ā + bṛh)</b>");
How can I read the Unicode contents from html files and show them in the QTextBrowser?
I shall be very thankful if someone shows me the buggy parts in my codes or tells me a better way of solving my problem.
You read a binary file into QString but do not tell the program, which bytes correspond to which unicode character, i.e. you don't specify the "encoding" aka. "codec".
To debug your problem, ask QTextStream
which codes it uses by default:
QTextStream textStream1(&file);
qDebug() << textStream1.codec()->name();
On my Linux system, that is already "UTF-8" but it might be different on your system. To force QTextStream interpreting the input as UTF-8, use QTextStream::setCodec.
来源:https://stackoverflow.com/questions/28495855/why-unicode-fonts-are-not-showing-properly-in-the-qtextbrowser-when-unicode-cont