QGraphicsView 绘画多边形
时间: 2023-10-29 10:59:45 浏览: 173
您可以通过继承 QGraphicsItem 类来实现自定义的多边形绘制。具体步骤如下:
1. 定义一个类继承自 QGraphicsItem,例如 MyPolygonItem。
2. 在 MyPolygonItem 中重载 boundingRect() 函数,返回多边形的包围盒。
3. 在 MyPolygonItem 中重载 paint() 函数,使用 QPainter 绘制多边形。
4. 在 QGraphicsView 中创建 MyPolygonItem 对象,并将其添加到场景中。
5. 在 QGraphicsView 中调用 fitInView() 函数,将多边形显示在视图中心。
以下是一个简单的示例代码:
```python
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QBrush, QColor, QPainter, QPolygonF
from PyQt5.QtWidgets import QGraphicsItem, QGraphicsView, QGraphicsScene, QApplication
class MyPolygonItem(QGraphicsItem):
def __init__(self, polygon):
super().__init__()
self.polygon = polygon
def boundingRect(self):
return self.polygon.boundingRect()
def paint(self, painter, option, widget):
brush = QBrush(QColor(255, 0, 0, 128))
painter.setBrush(brush)
painter.drawPolygon(self.polygon)
if __name__ == '__main__':
app = QApplication([])
view = QGraphicsView()
scene = QGraphicsScene()
view.setScene(scene)
polygon = QPolygonF([(-50, -50), (0, -100), (50, -50), (100, 0), (50, 50), (0, 100), (-50, 50), (-100, 0)])
item = MyPolygonItem(polygon)
scene.addItem(item)
view.fitInView(item, Qt.KeepAspectRatio)
view.show()
app.exec_()
```
运行以上代码,将会在窗口中显示一个八边形。您可以根据需要修改多边形的顶点坐标来绘制不同形状的多边形。
阅读全文
相关推荐










