2010-05-18 1138 views
23

我有一个QTextEdit框显示文本,我希望能够在同一个QTextEdit框中设置不同文本行的文本颜色。 (即线1可能是红色的,线2可能是黑色的等)QTextEdit具有不同的文本颜色(Qt/C++)

这是可能在QTextEdit框?如果不是,获得这种行为的最简单方法是什么?

谢谢。

回答

20

格式化为HTML使用文字,例如:

textEdit->setHtml(text); 

其中文本,是一个HTML格式化文本,用彩色线条包含等

23

只是快速增加:替代自己生成html,如果您以编程方式填充文本框,则使用textEdit->setTextColor(QColor&)。你可以自己创建QColor对象,或者使用Qt命名空间中的一种预定义颜色(Qt :: black,Qt :: red等)。它会将指定的颜色应用到您添加的任何文本,直到再次用另一个文本调用该颜色。

+2

这是迄今为止最简单的办法这样做。像日志记录那样起作用,每条线都根据消息的严重程度进行着色。 – SirDarius 2014-11-17 17:58:04

+0

但这只会使所有文字都呈现出来,我想用不同的颜色给每种颜色上色,你能帮我解决吗? – 2015-06-17 15:46:54

+1

如果您使用的是'textEdit'对象,它将使用不同的颜色为每个'append'调用的文本着色。 – 2016-04-19 16:38:13

28

只有为我工作的东西是HTML。

代码片段如下。

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

Link to doc

几个报价:

的QTextEdit是一个高级的所见即所得的浏览器/编辑器使用HTML 风格标志的支持富文本格式。它经过优化,可处理大型文档并快速响应用户输入。

文本编辑可以加载纯文本和HTML文件(HTML 3.2和4的子集)。

QTextEdit可以显示一个大的HTML子集,包括表格和图像。

这意味着大部分过时的标签,因此不包括任何当前CSS,所以我把这个:

// 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); 
+0

+1为设置属性,然后附加它 – Niklas 2013-08-12 04:16:06

6

扩展上https://stackoverflow.com/a/13287446/1619432

QTextEdit::append()插入新的段落与先前设置FontWeight/TextColor。 insertHTML()InsertPlainText()以避免插入新的段落(例如,为了在单行中实现不同的格式)不遵守字体/颜色设置。

而是使用QTextCursor

... 
// textEdit->moveCursor(QTextCursor::End); 
QTextCursor cursor(textEdit->textCursor()); 

QTextCharFormat format; 
format.setFontWeight(QFont::DemiBold); 
format.setForeground(QBrush(QColor("black"))); 
cursor.setCharFormat(format); 

cursor.insertText("Hello world!"); 
... 
+1

+ 1为'ìnsertText' – Niklas 2013-08-12 04:17:37

+0

这个答案教会了我新的东西 – 2015-06-17 17:16:38

+0

这个结束了为我工作。一行是一种颜色,下一行是不同的颜色。在这个例子中,在“Hello World”之后,你会放入'format.setForeground(QBrush(QColor(“white”)));''和'cursor.setCharFormat(format);'''cursor.insertText(“This line是白色的“);'。 – orbit 2016-03-20 08:19:53