Solved 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'sreload()
function) to remove the highlighting.It appears that I can fetch the text block from the
QTextDocument
and the correspondingQTextFormat
easily 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.
-
Hi,
Looks like a job for QSyntaxHighlighter.
-
@Chris-Kawa , @SGaist : Thank you very much for the suggestions. Will this also work for HTML text?
-
@Robert-Hairgrove said in Highlighting text in a QTextBrowser:
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!