Darius
Darius

Reputation: 155

Write HTML code in a QString

I'm working with the QT Creator and I would like to write a HTML code into a QString or to set a textEdit with setHtml(). The problem is, that I cannot really escape the special characters that come with the HTML code, e.g. :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-    html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'.Lucida Grande UI'; font-size:13pt;     font-weight:400; font-style:normal;">

How can I write something like this to a QString or directly set it to the textEdit?

I need this because my HTML text may change.

Upvotes: 3

Views: 4543

Answers (2)

You are asking simply how to escape a C string. You'll need to use an online tool, such as http://www.digitalcoding.com/tools/addslashes-stripslashes.html, or a command line tool like echo '<!DOCTYPE HTML PUBLIC...' | sed -e 's-"-\"-g' > escaped.c, or any text editor's replace functionality - say NotePad++'s.

Using such a tool, your string becomes:

<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-    html40/strict.dtd\">rn<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">rnp, li { white-space: pre-wrap; }rn</style></head><body style=\" font-family:\'.Lucida Grande UI\'; font-size:13pt;     font-weight:400; font-style:normal;\">

Just add a double quote at the beginning and at the end and you're all set:

auto foo = QStringLiteral("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-    html40/strict.dtd\">rn<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">rnp, li { white-space: pre-wrap; }rn</style></head><body style=\" font-family:\'.Lucida Grande UI\'; font-size:13pt;     font-weight:400; font-style:normal;\">");

Upvotes: 1

Andrea
Andrea

Reputation: 6125

There's an easy way for that! If you are using Qt5, just use

QString::toHtmlEscaped()

Example (from here):

QString plain = "#include <QtCore>";
QString html = plain.toHtmlEscaped();
// html == "#include &lt;QtCore&gt;"

If you are using Qt4:

Qt::escape

Example:

QString plain = "#include <QtCore>";
Qstring html = Qt::escape(plain);

Upvotes: 3

Related Questions