htmlqthtmlspecialcharsqtexteditrichtext

Convert QString to text with substitutes for HTML special characters (e.g. tags)


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?


Solution

  • 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()