How can I make a QString html-escaped
Asked Answered
N

3

28

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

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

Nerti answered 5/1, 2013 at 15:17 Comment(0)
D
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

Duleba answered 5/1, 2013 at 15:41 Comment(2)
Does not work for me because it does not encode german special characters like &auml; Is there a better function that knows ALL special characters?Harlamert
How do you reverse this? i.e., there is no QString::fromHtmlEscaped()Emmett
O
8

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

Ophthalmitis answered 25/7, 2013 at 4:38 Comment(0)
S
-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.

Seagirt answered 5/1, 2013 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.