最近做一个控制台输出的程序,中间定义了不同的输出登记,比如绿色为运行等级,黄色为警告等级,红色为严重错误等级,需要QTextEdit对传来的不同等级的文字进行不同的处理,效果如下:
void MainWindow::OutPutMsgToConsle(ConSleLevel level,const QString &strText)
{
//日志等级大于配置文件允许的最高等级,就返回
if (level > LocalConfig::GetInstance().GetCfgConsleLevel())
{
return;
}
m_Consle->append(strText);
//选中改行文字
QTextCursor cursor = m_Consle->textCursor();
cursor.setPosition(cursor.position(),QTextCursor::MoveAnchor);
cursor.setPosition(cursor.position() + strText.length(),QTextCursor::KeepAnchor);
cursor.select(QTextCursor::WordUnderCursor);
QTextCharFormat fmt;
//根据不同等级绘制不同颜色
QPainter p(this);
switch (level)
{
case ERROR_INFO:
fmt.setForeground(RGBRED);
break;
case WARMING_INFO:
fmt.setForeground(RGBYELLOW);
break;
case RUNNING_INFO:
fmt.setForeground(RGBGREEN);
break;
case DEBUG_INFO:
fmt.setForeground(Qt::black);
break;
default:
break;
}
cursor.mergeCharFormat(fmt);
cursor.clearSelection(); //撤销选中
cursor.movePosition(QTextCursor::EndOfLine); //cursor和anchor均移至末尾
}