0

I would like to use the magnifying glass (U+1F50E) Unicode symbol in a QLineEdit field. I figured out how to use 16-bit unicode symbols using QChar however I have no idea how to use a unicode symbol represented by 5 hex digits.

QLineEdit edit = new QLineEdit();
edit.setFont(QFont("Segoe UI Symbol"));
edit.setText(????);

So far I have tried:

edit.setText(QString::fromUtf8("\U0001F50E"));

Which gave the compiler warning:

warning C4566: character represented by universal-character-name '\UD83DDD0E' cannot be represented in the current code page

and showed up as: ??

I also tried:

edit.setText(QString("\U0001F50E"));

Which gave the compiler warning:

warning C4566: character represented by universal-character-name '\UD83DDD0E' cannot be represented in the current code page (1252)

And also gave: ??

I tried about everything you could try with QChar. I also tried switching the encoding of my CPP file and copying and pasting the symbol in, which didn't work.

Matthew Lueder
  • 953
  • 2
  • 12
  • 25

1 Answers1

8

You already know the answer - specify it as a proper UTF-16 string.

Unicode codepoints above U+FFFF are represented in UTF-16 using a surrogate pair, which is two 16bit codeunits acting together to represent the full Unicode codepoint value. For U+1F50E, the surrogate pair is U+D83D U+DD0E.

In Qt, a UTF-16 codeunit is represented as a QChar, so you need two QChar values, eg:

edit.setText(QString::fromWCharArray(L"\xD83D\xDD0E"));

or:

edit.setText(QString::fromStdWString(L"\xD83D\xDD0E"));

Assuming a platform where sizeof(wchar_t) is 2 and not 4.

In your example, you tried using QString::fromUtf8(), but you gave it an invalid UTF-8 string. For U+1F50E, it should have looked like this instead:

edit.setText(QString::fromUtf8("\xF0\x9F\x94\x8E"));

You can also use QString::fromUcs4() instead:

uint cp = 0x1F50E;
edit.setText(QString::fromUcs4(&cp, 1));
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770