Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight a string of text within a QTextEdit

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.

like image 647
Wylie Coyote SG. Avatar asked Feb 14 '13 22:02

Wylie Coyote SG.


People also ask

How do you highlight a section of text?

How to highlight text using your keyboard. To highlight with the keyboard, move to the starting location using the arrow keys. Then, hold down the Shift key, and press the arrow key in the direction you want to highlight. Once everything you want is highlighted, let go of the Shift key.

How do you highlight text in an article?

Highlighting ArticlesHighlight some text as you normally would and click on the "Highlight" link that appears in a pop-up. Alternatively, you can click on the highlight icon in the menu at the top of the screen. Any passage you select after that will be highlighted.

How do you highlight a single line of text?

To select a line of text, place your cursor at the start of the line, and press Shift + down arrow. To select a paragraph, place your cursor at the start of the paragraph, and press Ctrl + Shift + down arrow.

Can you highlight text in a text file?

The txt fileformat does not support any kind of formatting, so you cannot highlight anything in the traditional way. So the options you are left with is: you can use underscores. or you can use FULL-UPPERCASE.


1 Answers

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);
like image 148
hank Avatar answered Sep 17 '22 00:09

hank