The user will be able to put in some text into a QLineEdit in a Qt environment. However, these input texts can contain HTML special characters. My aim is to convert this text by replacing all HTML special character occurences with substitutes.

A similar case is found in PHP with the htmlspecialchars() function http://php.net/manual/en/function.htmlspecialchars.php.

The main reason I want to do this is because I want to display the user input in a richtext QTextEdit and I don't want the user to be able to change HTML and I wish to be able to use HTML special characters without too much hassle.

How can this be achieved?

有帮助吗?

解决方案

The easiest way I know, is to use QTextEdit::toHtml:

QString convert();
{
    QString s = lineEdit->text();
    QTextEdit textEdit;
    textEdit.setPlainText(s);
    QString ret = textEdit.toHtml();
    int firstClosingTag = ret.indexOf("</p></body></html>");
    int lastOpeningTag = ret.lastIndexOf(">", firstClosingTag);
    return ret.mid(lastOpeningTag + 1, firstClosingTag - lastOpeningTag - 1);
}

There are also two functions, which you could find useful:

Qt::convertFromPlainText() and Qt::escape()

其他提示

In Qt5, it's QString::toHtmlEscaped, e.g.:

QString a = "Hello, <span class=\"name\">Bear</span>!";
// a will contain: Hello, <span class="name">Bear</span>!

QString b = a.toHtmlEscaped();
// b will contain: Hello, &lt;span class=&quot;name&quot;&gt;Bear&lt;/span&gt;!

This is direct equivalent of the htmlspecialchars in PHP. It replaces the Qt::escape function (mentioned by Amartel), which does the same thing but is now obsolete.

The Qt::convertFromPlainText function (also mentioned by Amartel) still exists in Qt 5, but it does more than PHP's htmlspecialchars. Not only it replaces < with &lt;, > with &gt;, & with &amp;, " with &quot; but also does additional handling of whitespace characters (space, tab, line feed, etc) to make the generated HTML look visually similarly to the original plain text. Particularly, it may put <p>…</p>/<br> for linefeeds, non-breaking spaces for spaces and multiple non-breaking spaces for tabs. I.e. this function is not just htmlspecialchars, it's even more comprehensive than nl2br(htmlspecialchars($s)) combination.

Note that unlike the PHP's htmlspecialchars with ENT_QUOTES, none of the Qt functions listed in this answer replace single quote (') with &apos;/&#039;. So, for example, QString html = "<img alt='" + s.toHtmlEscaped() + "'>"; won't be safe, only QString html = "<img alt=\"" + s.toHtmlEscaped() + "\">"; will. (However, as < is replaced and ' has no special meaning outside <…>, something like QString html = "<b>" + s.toHtmlEscaped() + "</b>"; would also be safe.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top