对于这些情况,最简单的方法是使用HTML并插入标记:
<font color = "..."> </ font>
例子:
#include <QApplication>
#include <QDateTime>
#include <QPlainTextEdit>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
const std::map<QString, QColor> m_colours {{"red", QColor(Qt::red)},
{"blue", QColor(Qt::blue)},
{"green", QColor(Qt::green)}
};
class ProcessWidget: public QWidget{
Q_OBJECT
public:
ProcessWidget(QWidget *parent=nullptr):
QWidget(parent),
lay{this}
{
m_textedit.setReadOnly(true);
lay.addWidget(&m_textedit);
}
public slots:
void appendText(const QString & text){
QString html{text};
int j = 0;
bool start = true;
QString textColor;
while ((j = html.indexOf(QChar('\033'), j)) != -1) {
html.remove(j, 1);
QColor color;
for(auto & pair : m_colours){
if(html.mid(j).startsWith(pair.first)){
color = pair.second;
html.remove(j, pair.first.length());
}
}
if(start){
textColor = QString("<font color=\"%1\">").arg(color.name());
start = false;
}
else
textColor = QString("</font><font color=\"%1\">").arg(color.name());
html.insert(j, textColor);
j += 1+textColor.length();
}
html.append("</font>");
m_textedit.appendHtml(html);
}
private:
QPlainTextEdit m_textedit;
QVBoxLayout lay;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ProcessWidget w;
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&w](){
QString text = QString("\033redDateTime: %1 \033blueDate:%2 \033greenTime:%3")
.arg(QDateTime::currentDateTime().toString())
.arg(QDate().currentDate().toString())
.arg(QTime::currentTime().toString());
w.appendText(text);
});
timer.start(1000);
w.show();
return a.exec();
}
#include "main.moc"