Solved QByteArray to QString with embedded escape sequence
-
Problem: apostrophe is encoded as 0x26, 0x23, 0x33, 0x39, 0x3B in QByteArray not converting in QString
I have a QByteArray result extracted from xmp data in an image file:
result = {
0x42, 0x75, 0x66, 0x66, 0x6C, 0x65, 0x68, 0x65, 0x61, 0x64, 0x2C, 0x20,
0x50, 0x69, 0x70, 0x65, 0x72, 0x26, 0x23, 0x33, 0x39, 0x3B, 0x73, 0x20,
0x4C, 0x61, 0x67, 0x6F, 0x6F, 0x6E
}The following do not convert properly:
QString value = QTextCodec::codecForMib(106)->toUnicode(result); QString value = QString::fromStdString(result.toStdString());
value = Bufflehead, Piper' ;s Lagoon
but it should be: Bufflehead, Piper's Lagoon -
@Rory_1 said in QByteArray to QString with embedded escape sequence:
0x26, 0x23, 0x33, 0x39, 0x3B
That is
'
, as you have shown below. All is correct, nothing is wrong.'
is an HTML or XML entity for an apostrophe/single-quote character. No amount of std-stringing or codec-ing is going to convert that. OTOH if you slap that sequence into, say, an HTML page shown by a browser, or presumably aQTextEdit
orQLabel
, it should show as the apostrophe. -
@JonB Thanks!! This worked:
QTextEdit textEdit(value); return textEdit.toPlainText();
-
@Rory_1
That is a cheeky use of aQTextEdit
! :) -
@Rory_1 said in QByteArray to QString with embedded escape sequence:
QTextEdit textEdit(value); return textEdit.toPlainText();
That's quite clever!
If you need to do the conversion repeatedly, I suggest creating the QTextEdit on the heap to avoid repeated construction and destruction.
-
No need to use a QWidget - QTextDocument is enough here (Using QTextDocument::setHtml() / toPlainText())
-
@Christian-Ehrlicher
Ah, that is much better :)@Rory_1
Yes, you can convert HTML to plain text viaQTextEdit
. But if it's a standalone function to do just that, we prefer not to use a widget/UI method, @Christian-Ehrlicher'sQTextDocument
is preferable. -
Thanks very much! One thing I did not mention is this is in a worker thread pulling metadata out of images, and is not in the main gui thread. While the QTextEdit solution was working in release mode, it would not run in debug mode. The QTextDocument solution solves this issue as well.
QTextDocument d; d.setHtml(value)); return d.toPlainText();
@JKSH
Thanks for the tip about using the heap. :-) -
@Rory_1 said in QByteArray to QString with embedded escape sequence:
this is in a worker thread.... While the QTextEdit solution was working in release mode, it would not run in debug mode. The QTextDocument solution solves this issue as well.
The fact that it worked in Release mode was a fluke. Widgets cannot be used in worker threads, only in the GUI thread.
QTextDocument
, OTOH, is documented as reentrant so it can be safely used in a worker thread: https://doc.qt.io/qt-5/qtextdocument.html