Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTextEdit with different text colors (Qt / C++)

I have a QTextEdit box that displays text, and I'd like to be able to set the text color for different lines of text in the same QTextEdit box. (i.e. line 1 might be red, line 2 might be black, etc.)

Is this possible in a QTextEdit box? If not, what's the easiest way to get this behavior?

Thanks.

like image 550
user924 Avatar asked May 18 '10 13:05

user924


4 Answers

Just a quick addition: an alternative to generating the html yourself, if you're populating the text box programatically, is to use textEdit->setTextColor(QColor&). You can create the QColor object yourself, or use one of the predefined colours in the Qt namespace (Qt::black, Qt::red, etc). It will apply the specified colour to any text you add, until it is called again with a different one.

like image 155
badgerr Avatar answered Sep 22 '22 07:09

badgerr


The ONLY thing that worked for me was html.

Code snippet follows.

QString line = "contains some text from somewhere ..."     :     : QTextCursor cursor = ui->messages->textCursor(); QString alertHtml = "<font color=\"DeepPink\">"; QString notifyHtml = "<font color=\"Lime\">"; QString infoHtml = "<font color=\"Aqua\">"; QString endHtml = "</font><br>";  switch(level) {     case msg_alert: line = alertHtml % line; break;     case msg_notify: line = notifyHtml % line; break;     case msg_info: line = infoHtml % line; break;     default: line = infoHtml % line; break; }  line = line % endHtml; ui->messages->insertHtml(line); cursor.movePosition(QTextCursor::End); ui->messages->setTextCursor(cursor); 
like image 43
paie Avatar answered Sep 21 '22 07:09

paie


Use text formated as HTML, for example:

textEdit->setHtml(text);

where text, is a HTML formated text, contains with colored lines and etc.

like image 41
mosg Avatar answered Sep 21 '22 07:09

mosg


Link to doc

A few quotes:

QTextEdit is an advanced WYSIWYG viewer/editor supporting rich text formatting using HTML-style tags. It is optimized to handle large documents and to respond quickly to user input.

.

The text edit can load both plain text and HTML files (a subset of HTML 3.2 and 4).

.

QTextEdit can display a large HTML subset, including tables and images.

This means mostly deprecated tags and as such does not include any current CSS, so I turned to this:

// save    
int fw = ui->textEdit->fontWeight();
QColor tc = ui->textEdit->textColor();
// append
ui->textEdit->setFontWeight( QFont::DemiBold );
ui->textEdit->setTextColor( QColor( "red" ) );
ui->textEdit->append( entry );
// restore
ui->textEdit->setFontWeight( fw );
ui->textEdit->setTextColor( tc );
like image 36
none Avatar answered Sep 19 '22 07:09

none