Why Unicode fonts are not showing properly in the QTextBrowser when Unicode contents are read from an html file?

给你一囗甜甜゛ 提交于 2019-12-02 08:27:07

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!