QGraphicsScene QGraphicsItem 绘制文本
时间: 2023-11-06 12:17:54 浏览: 280
在QGraphicsScene和QGraphicsItem中绘制文本,可以使用QGraphicsTextItem类。QGraphicsTextItem是QGraphicsItem的子类,可以用于显示文本和HTML格式的文本。可以通过以下步骤在场景中添加QGraphicsTextItem:
1. 创建QGraphicsTextItem对象,并设置文本内容和位置
```python
text_item = QGraphicsTextItem("Hello World")
text_item.setPos(x, y) # 设置文本位置
```
2. 将QGraphicsTextItem添加到场景中
```python
scene.addItem(text_item) # 添加文本到场景中
```
完整代码示例:
```python
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsTextItem, QApplication
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
# 创建场景和视图
scene = QGraphicsScene()
view = QGraphicsView(scene)
view.setWindowTitle("Text Item Example")
view.resize(400, 300)
view.show()
# 添加文本到场景中
text_item = QGraphicsTextItem("Hello World")
text_item.setPos(100, 100)
text_item.setDefaultTextColor(Qt.red) # 设置文本颜色
scene.addItem(text_item)
sys.exit(app.exec_())
```
在上面的示例中,我们创建了一个场景和视图,然后添加了一个文本项到场景中,并设置了文本的位置和颜色。运行代码,可以看到在场景中添加了一个红色的文本项。
阅读全文
相关推荐
















