开发中经常遇到需要设置文字颜色的问题,比如输出日志,错误信息要标识为红色;正常提示要标识为黑色。下面就以两种方法实现:
1、直接设置行颜色:
QTextEdit* pTextEdit = GetCenterWidget()->GetOut();
QColor oldColor = pTextEdit->textColor();
pTextEdit->setTextColor(mode == 0 ? Qt::black : Qt::red);
pTextEdit->append(textError);
pTextEdit->setTextColor(oldColor);
2、使用QTextCharFormat设置颜色:
pTextEdit->append(textError);
QTextCursor cursor = pTextEdit->textCursor();
cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
cursor.setPosition(cursor.position() + textError.length(), QTextCursor::KeepAnchor);
cursor.select(QTextCursor::LineUnderCursor);//使用WordUnderCursor可能导致第一次使用时该行只有部分颜色被标识,因此要使用LineUnderCursor
QTextCharFormat fmt;
fmt.setForeground(QBrush(mode == 0 ? Qt::black : Qt::red));
cursor.mergeCharFormat(fmt);
cursor.clearSelection();
cursor.movePosition(QTextCursor::EndOfLine);
pTextEdit->mergeCurrentCharFormat(fmt);