QGraphicsTextItem 颜色
时间: 2024-01-24 19:08:22 浏览: 26
QGraphicsTextItem 的颜色可以通过 setDefaultTextColor() 方法来设置,默认的颜色是黑色。该方法接受一个 QColor 参数,表示文本的颜色。例如,下面的代码将 QGraphicsTextItem 的颜色设置为红色:
```
QGraphicsTextItem *textItem = new QGraphicsTextItem("Hello World");
textItem->setDefaultTextColor(QColor(Qt::red));
```
除了设置默认颜色外,还可以使用 setPlainText() 方法设置文本的颜色,该方法接受一个 QTextDocument 参数。例如,下面的代码将 QGraphicsTextItem 的前 5 个字符设置为红色:
```
QGraphicsTextItem *textItem = new QGraphicsTextItem("Hello World");
QTextCursor cursor = textItem->textCursor();
cursor.movePosition(QTextCursor::Start);
cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, 5);
QTextCharFormat charFormat;
charFormat.setForeground(QColor(Qt::red));
cursor.setCharFormat(charFormat);
```
这里使用了 QTextCursor 类的方法来选择文本的前 5 个字符,并使用 QTextCharFormat 类的方法设置文本的前景色。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)