在文本浏览器中设置不同的颜色

时间:2014-08-08 08:14:38

标签: qt

我通过http get从服务器获取一个文件,这是一个diff文件。 我想将文本颜色设置为红色以便删除和绿色以便添加可能正在寻找第一个字符< />。 如何在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

2 个答案:

答案 0 :(得分:1)

您可以使用QTextBrowser课程来展示您的内容。它支持HTML,因此您可以使用一些HTML代码来更改特定文字的颜色。

您需要注意的是HTML uses < and > characters for tags。所以我们必须告诉它这些不是标签,而是我们希望在屏幕上显示的字符。

以下是我展示如何做到这一点的一个小例子:

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);

答案 1 :(得分:0)

您可以使用<span> html标记为部分文字设置颜色:

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

textBrowser->setHtml(styledString);