qtpyqtqtextbrowser

Unexpected results when appending links and line breaks to QTextBrowser


I'm getting some unexpected results when appending strings with links and line breaks to a QTextBrowser instance.

    browser = QTextBrowser()
    browser.append('foo <a href="https://example.com">example.com</a> bar')
    browser.append('foo\n<a href="https://example.com">example.com</a>')
    browser.append('\n<a href="https://example.com">example.com</a>\nbar')
    browser.append('\nfoo\nbar')

This will look like this:

enter image description here

The first and last 'appends' are controls and behave as expected. But when line breaks and links are combined in one string, strange things are happening.

For the second 'append' the link is not being 'linkefied', and for the third one, the two line breaks are ignored.

What's happening here?


Solution

  • It works exactly like setText():

    The text can be plain text or HTML and the text edit will try to guess the right format.

    The second example finds a new line character after normal "word" chatacters, so it "guesses" that the string contains plain text. The third example shows the link because in HTML new line characters are (normally) ignored. If you want to append HTML, use insertHtml() or the QTextCursor interface.