PDA

View Full Version : How to set text and font in qTextEdit?



JuKu
27th September 2009, 20:58
Hi,

My very first Qt application calls for a text display, built by the application. Parts of it needs to be in color.

How can I:

-set the color or font of text in qTextEdit, by line&char? For example, start from line 5, character 4 and make next 10 characters bold with gray background?

-replace said characters with some other text, keeping the formatting?

And finally, am I using the right widget in the first place?

Thank you!

wysota
27th September 2009, 21:03
Look at QTextCursor and QTextCharFormat classes.

JuKu
28th September 2009, 16:27
Thank you! The Qt documentation is very good, but there is lots of it. Your keywords pointed me to the right direction.

To save other noobies an hour or two, here is where the keys were found:
All Overviews and HOWTOs (http://qt.nokia.com/doc/4.5/overviews.html) in general and especially, Supported HTML Subset (http://qt.nokia.com/doc/4.5/richtext-html-subset.html). I hadn't realized the qTextEdit used HTML inside!

Here is some example code:


ui->TextEdit->setText("1234567890<br>1234567890<br>line3");
QTextCursor cursor(ui->TextEdit->document());
cursor.setPosition(15, QTextCursor::MoveAnchor); // Go to 4th character of second line; the <br> counts as one character.
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 3); // select three charaters
QString s=cursor.selectedText();
cursor.insertHtml("<FONT color=green style=\"BACKGROUND-COLOR: yellow\">"+s+"</FONT>"); // make them ugly

The more familiar I get with Qt, the more I like it. :)