Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Highlighting text in a QTextBrowser
I am implementing a search function for my help viewer based on
QTextBrowser. What I would like to do, once a page has been loaded containing the search item text, is to highlight each of the occurrences of the text with background color = yellow. The user can then reload the document (hitting F5 calls the widget's
reload()function) to remove the highlighting.
It appears that I can fetch the text block from the
QTextDocumentand the corresponding
QTextFormateasily enough, but it seems that there is no way to edit it (i.e., change the background color of a selection)?
What would be the best way to implement this?
If all you have is plain text you can just replace the formatting for the selected part like this:
QTextCharFormat fmt; fmt.setBackground(Qt::yellow); QTextCursor cursor(textBrowser->document()); cursor.setPosition(start_pos, QTextCursor::MoveAnchor); cursor.setPosition(end_pos, QTextCursor::KeepAnchor); cursor.setCharFormat(fmt);
If you have some formatting you will have to iterate over text blocks in that range, get the format from them, modify the color and set back.
Looks like a job for QSyntaxHighlighter.
Will this also work for HTML text?
Html is only an input/output format. Internally QTextBrowser stores content in QDocument the same whether it's plaint text, rich text, markdown or html.
@Chris-Kawa Thanks! Now I need to test this.
@Chris-Kawa ... Thank you, this works like a charm!