Sahil Sareen
Sahil Sareen

Reputation: 1834

Setting different colors in text browser

I get a file via http get from the server which is a diff file. I want to set the text color red for removed and green for added maybe looking for the first character < / >. How to do that in Qt?

> 10 permit ip 10.10.0.0/16 20.20.20.0/24
> 20 deny ip any any
34,35c28
< 10 permit ip 10.10.10.4/30 20.20.20.0/31
< 20 permit ip 10.10.10.0/29 20.20.20.0/30

Upvotes: 0

Views: 2686

Answers (2)

thuga
thuga

Reputation: 12901

You can use QTextBrowser class to show your contents. It supports HTML, so you can use some HTML code to change the color of specific text.

Something you need to note, is that HTML uses < and > characters for tags. So we have to tell it that these are not tags, but characters we wish to display on the screen.

Here is a small example I made to show how you could do this:

QStringList text_list; // I use this to store lines of text
text_list << "> Added this row";
text_list << "> Added this row";
text_list << "< Removed this row";
text_list << "> Added this row";

//the following string is what we will use to style our text
QString html_style("<style>"
                         "p.add{color: green; margin: 0; padding: 0;}"
                         "p.remove{color: red; margin: 0; padding: 0;}"
                         "</style>");

QString format_add = "<p class=\"add\">%1</p>"; // we use these to make formatting easier
QString format_remove = "<p class=\"remove\">%1</p>"; // basically helps us add tags before and after our text

QString text; // this is a variable we will use to append our text as HTML code

for(int i = 0; i < text_list.length(); i++)
{
    if(text_list[i].startsWith(">")) // detect if the line was added
        text.append(format_add.arg(text_list[i].replace(">", "&#62;"))); // add the line in our html code, but replace > character with a character entity

    else if(text_list[i].startsWith("<")) // detect if the line was removed
        text.append(format_remove.arg(text_list[i].replace("<", "&#60;"))); // add the line in our html code, but replace < character with a character entity
}

ui->textBrowser->setHtml(html_style + text);

Upvotes: 1

Nejat
Nejat

Reputation: 32635

You can use <span> html tag to set a color for part of text :

QString styledString="<span style=\" font-size:8pt; font-weight:600; color:#FF0c32;\" > ";
styledString.append(myString);
styledString.append("</span>");

textBrowser->setHtml(styledString); 

Upvotes: 0

Related Questions