Qt utf-8 encoding issue

Viewed 65
    #include <iostream>

    #include <QString>

    using namespace std;
    
    int main()
    {
    
        QString qstr = QString::fromUtf8("      ");
        cout << qstr.length() << std::endl;
        for (QChar c : qstr) cout << QString(c).toStdString() << endl;
    }

Got output:

19

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

?

Expected output:

11

Qt version:

Package: qt5-default Architecture: amd64 Version: 5.5.1+dfsg-16ubuntu7.7 Multi-Arch: same Priority: optional Section: universe/libs Source: qtbase-opensource-src Origin: Ubuntu

How to fix this?

1 Answers

QString stores a string of 16-bit QChars https://doc.qt.io/qt-5/qstring.html

" " string has 4 byte char. following code can be used:

QString str = QString::fromUtf8("      ");
cout << "uint 32b: " << str.toUcs4().size() << endl;


foreach (const uint &  ucsChar, str.toUcs4())
    cout << QChar::decomposition(ucsChar).toStdString() << endl;
Related