编写一个widget框架的qgraphicsview
时间: 2024-05-04 22:15:26 浏览: 90
qgraphicsview
4星 · 用户满意度95%
这里是一个简单的QGraphicsView widget框架的实现示例:
```python
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen, QBrush, QColor
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene
class MyWidget(QGraphicsView):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self._scene = QGraphicsScene(self)
self.setScene(self._scene)
self.setRenderHint(QPainter.Antialiasing)
def paintEvent(self, event):
super(MyWidget, self).paintEvent(event)
painter = QPainter(self.viewport())
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(Qt.NoPen)
painter.setBrush(QBrush(QColor(255, 255, 255)))
painter.drawRect(self.rect())
def drawLine(self, start, end, color):
pen = QPen(QColor(color))
pen.setWidth(2)
self._scene.addLine(start.x(), start.y(), end.x(), end.y(), pen)
def drawRect(self, pos, size, color):
pen = QPen(QColor(color))
pen.setWidth(2)
self._scene.addRect(pos.x(), pos.y(), size.width(), size.height(), pen)
def drawEllipse(self, pos, size, color):
pen = QPen(QColor(color))
pen.setWidth(2)
self._scene.addEllipse(pos.x(), pos.y(), size.width(), size.height(), pen)
def clear(self):
self._scene.clear()
```
这个框架实现了一个自定义的QGraphicsView类,它支持绘制直线、矩形和椭圆,并提供了清除场景的方法。在paintEvent()方法中,我们使用QPainter绘制了一个白色的背景,以便更好地显示绘制的图形。
阅读全文