How to correctly append string to string with surrogate pairs (utf16)?



  • I have a QString which includes a surrogate pair and I want to append some other string to it.

    QString convertUnicodeToString(uint32_t symbol)
    {
    QString str;
    QChar charArray[2];
    charArray[0] = QChar::highSurrogate(symbol);
    charArray[1] = QChar::lowSurrogate(symbol);
    str = QString(charArray, 2);
    return str;
    }

    QString a = "a";
    QString b = convertUnicodeToString(QChar(0x1d160));

    Then I use a painter to draw the text in a qwidget.
    Method 1: a.append(b) works fine. I get the letter 'a' followed by a music symbol
    Method 2: b.append(a) doesn't work. I get the two symbols on the same place.

    So at the moment, to get them next to each other, I'll have to do this:
    Method 3: b.append(" ").append(a) (two blank spaces is needed!)

    Do I need to insert '\0', BOM or some other thing to mark the end of the surrogate-pair-part of the string?
    There must be a better way to do this than method 3?


  • Qt Champions 2016

    uint32_t symbol;
    
    QString a = "a";
    a += QChar(symbol);
    

    ?
    QString already keeps the data internally as unicode.



  • Thanks for your reply, but I don't get this to work for:
    uint32_t symbol = 0x1D161;
    It shows a + some chinese character?


  • Qt Champions 2016

    Well, this is larger than a single short, so you'd need to use QString::fromUtf16 if you need decoding the utf16.



  • Ok, maybe there is something I don't understand here:) or maybe the problem is related to the font or painter.

    When I try this:
    QString test = "a";
    test+=QString::fromUtf16(u"\U0001D161");
    test+="a";
    painter.drawText(500,500,test);
    0_1506205443773_screenshot_qt.png

    So, I get the correct symbols (a + musical note +a), but the last two characters (musical note+a) are still drawn at the same place like in method 2 above.

    Also, when I measure the width:
    QFontMetrics f = painter.fontMetrics();
    f.width(QString::fromUtf16(u"\U0001D161")); //returns 0
    f.boundingRect(QString::fromUtf16(u"\U0001D161")).width(); //returns 19

    Is it possible that QPainter::drawText() isn't moving when drawing the next character, because the width is 0?


  • Qt Champions 2016

    @huse said in How to correctly append string to string with surrogate pairs (utf16)?:

    Is it possible that QPainter::drawText() isn't moving when drawing the next character, because the width is 0?

    Yes, but I really don't know why that is. Perhaps it's some problem with the font metrics, i.e. your font doesn't support (well) that particular character, but to be completely honest I'm just speculating.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.