Search code examples
c++qtpyqt

QTextEdit can't insertPlainText after insertHtml


QTextEdit can't insertPlainText after insertHtml. QTextEdit inserts html and then inserts plain text. Plain text is still displayed in html format. Is this a bug? Or am I using the wrong method.

enter image description here

I want to add html first and then plain text, and they will display properly, what do I do.


Solution

  • The documentation is quite clear.

    QTextEdit::insertPlainText() says that:

    It is equivalent to edit->textCursor().insertText()

    Which, in turn, clearly says that:

    Inserts text at the current position, using the current character format.

    So, follow the simple procedure:

    1. insert the HTML;
    2. get the textCursor();
    3. use setCharFormat() with an empty QTextCharFormat() instance;
    4. set the text cursor again to the text edit with setTextCursor() so that the format is actually applied for new insertions;
    5. call insertPlainText();

    I strongly recommend you to read the documentation about to the Qt rich text processing and the related topics, such as its structure and classes (starting from QTextDocument and QTextCursor).