How to highlight a string of text within a QTextEdit

Wylie Coyote SG. picture Wylie Coyote SG. · Feb 14, 2013 · Viewed 12.3k times · Source

I'm a student programmer currently developing an application for work using Qt4. I am building an equation editor and I'm having issues attempting to highlight a string within my QTextEdit field. I have a function that parses through the QTextEdit string and returns an a start and end integer of where an error is located. My original strategy was to use HTML tags at these two points to highlight the error. Unfortunately there appears to be an issue with html tagging and the equation syntax.

What I think I need is a strategy that relies on Qt's library to set a background color between these two indices. I began looking a QSyntaxHighlighter; however I think that this is more for highlighting using a predefined set of laws and not for just grabbing up anything between a & b and setting the background color. If I can use syntax highlighter please provide me with and example or reference as I have already read through the documentation and didn't find anything.

Thanks for any help in advance!

P.S. Just to emphasize on the html compatibility issues; html becomes problematic due to multiple < and > signs used.

Answer

hank picture hank · Feb 15, 2013

You can use QTextCursor and QTextCharFormat for it:

QTextEdit *edit = new QTextEdit;
...
int begin = ...
int end = ...
...

QTextCharFormat fmt;
fmt.setBackground(Qt::yellow);

QTextCursor cursor(edit->document());
cursor.setPosition(begin, QTextCursor::MoveAnchor);
cursor.setPosition(end, QTextCursor::KeepAnchor);
cursor.setCharFormat(fmt);