QTextEdit具有不同的文本颜色(Qt/C++)

use*_*924 27 c++ qt colors qtextedit

我有一个QTextEdit显示文本的框,我希望能够在同一个QTextEdit框中为不同的文本行设置文本颜色.(即第1行可能是红色,第2行可能是黑色等)

这可能在QTextEdit盒子里吗?如果没有,获得此行为的最简单方法是什么?

谢谢.

小智 32

为我工作的事情是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);
Run Code Online (Sandbox Code Playgroud)


bad*_*err 27

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

  • 这是迄今为止最简单的解决方案.就像一个魅力,例如用于记录,其中每一行根据消息的严重性着色. (2认同)

mos*_*osg 24

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

textEdit->setHtml(text);
Run Code Online (Sandbox Code Playgroud)

其中的文字,是HTML格式化文本,用彩色线条等含有


小智 11

链接到doc

一些引言:

QTextEdit是一个高级的WYSIWYG查看器/编辑器,支持使用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 );
Run Code Online (Sandbox Code Playgroud)


han*_*dle 8

/sf/answers/930121251/上进行扩展:

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!" );
...
Run Code Online (Sandbox Code Playgroud)

  • 这个答案教会了我新的东西 (3认同)