PYQT5中,在QGraphicsView鼠标左键点击绘制点,并且绘制的点也会在光标箭头的位置,下一个点与上一个点用一条线段连接,鼠标右键可以实现停止绘制线段和撤销绘制两个功能,鼠标滚轮可以实现QGraphicsView的放大与缩小,并且放大缩小后绘制点时位置还是在光标箭头处,请给出相关python代码
时间: 2023-05-12 08:03:44 浏览: 240
QGraphicsView以鼠标点实现放大缩小、拖拽
以下是实现上述功能的Python代码:
```python
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MyView(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.pen = QPen(Qt.black, 2)
self.line = None
self.points = []
self.is_drawing = False
self.is_undo = False
self.setRenderHint(QPainter.Antialiasing)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setInteractive(True)
self.setMouseTracking(True)
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.is_drawing = True
self.points.append(event.pos())
self.line = QGraphicsLineItem(QLineF(event.pos(), event.pos()))
self.line.setPen(self.pen)
self.scene.addItem(self.line)
elif event.button() == Qt.RightButton:
if self.is_drawing:
self.is_undo = True
self.is_drawing = False
self.scene.removeItem(self.line)
self.line = None
self.points = []
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.is_drawing:
self.line.setLine(QLineF(self.points[-1], event.pos()))
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.is_drawing:
self.points.append(event.pos())
self.is_drawing = False
super().mouseReleaseEvent(event)
def wheelEvent(self, event):
if event.angleDelta().y() > 0:
self.scale(1.1, 1.1)
else:
self.scale(0.9, 0.9)
super().wheelEvent(event)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Z and event.modifiers() == Qt.ControlModifier:
if self.is_undo:
self.is_undo = False
self.is_drawing = True
self.points.pop()
self.line = QGraphicsLineItem(QLineF(self.points[-1], self.points[-2]))
self.line.setPen(self.pen)
self.scene.addItem(self.line)
super().keyPressEvent(event)
if __name__ == '__main__':
app = QApplication([])
view = MyView()
view.show()
app.exec_()
```
这段代码实现了在QGraphicsView中绘制线段的功能,同时支持鼠标滚轮缩放和撤销绘制。具体实现方式是在鼠标左键按下时记录鼠标位置,创建一个QGraphicsLineItem对象,并将其添加到场景中;在鼠标移动时更新线段的终点位置;在鼠标释放时记录终点位置,并停止绘制。在鼠标右键按下时,如果正在绘制,则撤销绘制;在鼠标滚轮滚动时,根据滚动方向进行缩放;在按下Ctrl+Z时,如果有绘制操作可以撤销,则撤销最后一次绘制。
阅读全文