好像没人做这个,我搞了个前景色的分享下。
1、在append()字符串时设置颜色
2、在append()字符串前判断颜色,并把\033[31m此类字符删除
代码如下:
typedef struct{ QString colStr; QColor col; }colStr_t; static const colStr_t G_colorParts[] = { {"\033[0m",Qt::black}, {"\033[1m",Qt::black}, {"\033[2m",Qt::black}, {"\033[30m",Qt::black}, {"\033[31m",Qt::red}, {"\033[32m",Qt::green}, {"\033[33m",Qt::yellow}, {"\033[34m",Qt::blue}, {"\033[35m",Qt::magenta}, {"\033[36m",Qt::cyan}, {"\033[37m",Qt::color0}, {"\033[40m",Qt::black}, {"\033[41m",Qt::black}, {"\033[42m",Qt::black}, {"\033[43m",Qt::black}, {"\033[44m",Qt::black}, {"\033[45m",Qt::black}, {"\033[46m",Qt::black}, {"\033[47m",Qt::black} }; void MainWindow::setStdout(QString txt) { // 先保存当前的文字颜色 auto cur_text_color = ui->teStdout->textColor(); // 设置当前行要使用的颜色 #if 1 if(txt.startsWith("\033[")){ QString colStr; int i,start = txt.indexOf('m'); if(start != -1){ colStr = txt.left(start+1); txt = txt.right(txt.length()-start-1); txt = txt.trimmed(); } start = txt.indexOf("\033[0m"); if(start != -1){ txt = txt.remove(start,4); } for(i=0;i<ARRAY_SIZE(G_colorParts);i++){ if(G_colorParts[i].colStr == colStr){ ui->teStdout->setTextColor(G_colorParts[i].col); break; } } if(i == ARRAY_SIZE(G_colorParts)) ui->teStdout->setTextColor(Qt::black); } #else // 用正则表达式来替换 int i; QString colStr; QStringList list; QRegularExpression reg("\\033\\[[\\d;]+m"); QRegularExpressionMatchIterator it = reg.globalMatch(txt); while (it.hasNext()){ QRegularExpressionMatch match2 = it.next(); list << match2.captured(0); } if(list.count() > 0){ colStr = list[0]; for(i=0;i<ARRAY_SIZE(G_colorParts);i++){ if(G_colorParts[i].colStr == colStr){ ui->teStdout->setTextColor(G_colorParts[i].col); break; } } if(i == ARRAY_SIZE(G_colorParts)) ui->teStdout->setTextColor(Qt::black); // 删除颜色字段 txt = txt.remove(reg); } #endif // 写入一行内容 ui->teStdout->append(txt); // 最后恢复原来的颜色 ui->teStdout->setTextColor(cur_text_color); }
效果: