下述代码将实现:QString msg1 在 QTextEdit显示为红色,其余内容显示为黑色。
项目头文件:
include <QtWidgets/QMainWindow>
include <QTextEdit>//在Qt项目的主程序类中添加:
private:void appendColoredText(QTextEdit *textEdit, const QString &text, const QColor &color) {// 创建一个 QTextCharFormat 对象QTextCharFormat format;format.setForeground(color); // 设置前景色// 创建一个 QTextCursorQTextCursor cursor = textEdit->textCursor();cursor.movePosition(QTextCursor::End); // 移动到文本结尾textEdit->setTextCursor(cursor); // 设置 Cursor// 应用格式并插入文本cursor.insertText(text, format); QTextCharFormat format2;format2.setForeground(Qt::black); // 设置黑色-表示接下来内容为黑色cursor.insertText("\n", format2); // 添加换行}
项目cpp文件:
//此处为使用示例// 添加红色文本-使用自定义函数appendColoredText(textEdit, "This is msg1 in red.", Qt::red);//添加默认的黑色文本-使用TextEdit的自带方法ui->textEdit->append("This is msg2 in black.");//或者ui.textEdit->append("This is msg2 in black.");
上述代码可灵活运用实现特定文本以不同颜色添加显示。
补充:QLable实现指定颜色显示:
QPalette pe;
pe.setColor(QPalette::WindowText,Qt::red);//设置为红色
ui->lable_1->setPalette(pe);
ui->lable_1->setText("显示为红色");