Take the 2-minute tour ×

I would like to convert a QString containing Unicode characters to plain HTML text. For instance "私" would become "&#31169;".

Is there such a functionality in Qt? I found the function QString Qt::escape ( const QString & plain ) but it only converts HTML metacharacters <, >, &, and ".

There seams to be a lot of Qt classes and functions for encoding and internationalization but I just don't know where to look at.

share|improve this question

3 Answers 3

You should take a look at

QString QUrl::toString(FormattingOptions options = FormattingOptions( PrettyDecoded )) const
QByteArray QUrl::toPercentEncoding ( const QString & input, const QByteArray & exclude = QByteArray(), const QByteArray & include = QByteArray() )

Qt online doc QUrl::toString , QUrl::toPercentEncoding


share|improve this answer
Interesting... But not what I was looking for. I don't need a percent encoding but an HTML ampersand encoding, like in my example. –  Neptilo Dec 12 '12 at 21:04
我的例子事实上应该是日语的『我』。 :) –  Neptilo Dec 12 '12 at 21:21

I found various Qt methods here and there, and decided to create my own encoding function:

QString ampersand_encode(const QString& str){

    QString chr;
    QStringList list = QStringList();

    for (int i = 0; i < str.size(); ++i) {
        chr = QString(str[i]);
        list << "&#x" + QString(chr.toUtf8().toHex()) + ";";

    return list.join("");

It almost works. It works for ASCII characters but when I try it with other Unicode characters I only get Korean characters. Why? I feel there's not much to change but I don't know what. Also, any improvement of my code would be appreciated. :)

share|improve this answer
In fact this worked correctly, but my tests were wrong. I entered text directly in my code and Unicode characters were split in 8-bit characters. Now that I enter text in a QLineEdit, it works much better. I also found out that hex codes (in the form &#x...;) are not displayed properly, whereas decimal codes (&#...;) are. –  Neptilo Dec 21 '12 at 15:41
up vote 0 down vote accepted

I asked in Qt Centre forums and someone gave me the answer I needed. Here it is.

Here is the code that was suggested and that solved my problem:

QString ampersand_encode(const QString &string) {
  QString encoded;
  for(int i=0;i<string.size();++i) {
    QChar ch = string.at(i);
    if(ch.unicode() > 255)
      encoded += QString("&#%1;").arg((int)ch.unicode());
      encoded += ch;
  return encoded;
share|improve this answer
please include the main part of any linked information so that if/when the link goes dead your answer isn't useless to future visitors. –  rubenvb Dec 23 '12 at 14:42
Done. Thanks for the advice –  Neptilo Dec 24 '12 at 15:31

Your Answer


