28

How do I escape/sanitize a QString that contains HTML?

I.e. showInBroswser(escaped(str)) == showInNotepad(str);

sashoalm
  • 75,001
  • 122
  • 434
  • 781

3 Answers3

54

Qt 5

Use QString::toHtmlEscaped()

QString src;
Qstring html = src.toHtmlEscaped();
showInBrowser(html) == showInNotepad(str);

Reference: http://doc.qt.io/qt-5/qstring.html#toHtmlEscaped

Qt 4

Use Qt::escape.

#include <QtGui/qtextdocument.h>

QString src;
Qstring html = Qt::escape(src);
showInBrowser(html) == showInNotepad(str);

Reference: http://doc.qt.io/qt-4.8/qt.html#escape

Community
  • 1
  • 1
PenguinCoder
  • 4,335
  • 1
  • 26
  • 37
  • Does not work for me because it does not encode german special characters like ä Is there a better function that knows ALL special characters? – feedc0de Jan 13 '16 at 09:44
  • 3
    How do you reverse this? i.e., there is no `QString::fromHtmlEscaped()` – Phlucious Oct 05 '18 at 17:58
8

Just to bring this answer up with the times, Qt 5.1 has QString::toHtmlEscaped().

cbuchart
  • 10,847
  • 9
  • 53
  • 93
gremwell
  • 1,419
  • 17
  • 23
-2

If you want to insert plain text to a QTextEdit you can use:

void QTextEdit::insertPlainText ( const QString & text );

and, for example, to modify the color :

void QTextEdit::setTextColor ( const QColor & c ); 

And similar for the font or other property of the text...

Hope that helps.

lucasmrod
  • 260
  • 2
  • 9