QPlainTextEdit c++ 设置字体颜色
时间: 2023-06-20 07:07:10 浏览: 309
可以通过设置 QTextCharFormat 对象的属性来实现 QPlainTextEdit 中文本的颜色设置。以下是一个简单的示例代码:
```c++
QPlainTextEdit *textEdit = new QPlainTextEdit(this);
QTextCharFormat format;
format.setForeground(QBrush(Qt::red)); // 设置前景色为红色
textEdit->setCurrentCharFormat(format); // 设置当前字符格式
textEdit->insertPlainText("Hello, world!"); // 插入文本
```
上述代码设置了 QPlainTextEdit 中的文本颜色为红色。如果需要设置不同部分文本的颜色,可以在插入文本时使用不同的 QTextCharFormat 对象。例如:
```c++
QPlainTextEdit *textEdit = new QPlainTextEdit(this);
QTextCharFormat redFormat;
redFormat.setForeground(QBrush(Qt::red));
QTextCharFormat blueFormat;
blueFormat.setForeground(QBrush(Qt::blue));
textEdit->insertPlainText("This text is ");
textEdit->setCurrentCharFormat(redFormat);
textEdit->insertPlainText("red");
textEdit->setCurrentCharFormat(blueFormat);
textEdit->insertPlainText(" and this text is blue.");
```
上述代码将 "red" 设置为红色,将 "blue" 设置为蓝色。如果需要设置更多属性,可以查看 QTextCharFormat 类的其他方法。