写一个QGraphicsView
时间: 2023-10-29 08:59:46 浏览: 75
QGraphicsView.7z
下面是一个简单的QGraphicsView的示例代码:
```python
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush, QColor
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene
class MyView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.setSceneRect(-200, -200, 400, 400)
self.setBackgroundBrush(QBrush(QColor(255, 255, 255)))
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.drawItems()
def drawItems(self):
rect_item = self.scene.addRect(-100, -100, 200, 200)
rect_item.setBrush(QBrush(QColor(255, 0, 0)))
rect_item.setPen(Qt.NoPen)
ellipse_item = self.scene.addEllipse(-50, -50, 100, 100)
ellipse_item.setBrush(QBrush(QColor(0, 255, 0)))
ellipse_item.setPen(Qt.NoPen)
if __name__ == '__main__':
app = QApplication([])
view = MyView()
view.show()
app.exec_()
```
这个示例中创建了一个自定义的QGraphicsView,它包含了一个QGraphicsScene,并且设置了一些属性,例如渲染提示、场景矩形、背景刷、滚动条策略、拖动模式等。在drawItems方法中向场景中添加了两个图形项:矩形和椭圆,它们分别设置了填充刷和无边框线条。最后通过QApplication来运行程序并显示视图。
阅读全文