pyqt5 graphicsView 重写 mousePressEvent、mouseMoveEvent、mouseReleaseEvent,进行框选红色矩形,并返回实际坐标
时间: 2023-07-10 18:21:15 浏览: 160
QT学习之重写鼠标移动事件
好的,下面是一个示例程序,展示如何在 PyQt5 中使用 GraphicsView 进行红色矩形框选,并返回选中区域的实际坐标:
```python
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class GraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setDragMode(QGraphicsView.RubberBandDrag)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = event.pos()
self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rubberBand.setStyleSheet("background-color: rgba(255, 0, 0, 50);")
self.rubberBand.show()
super(GraphicsView, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.rubberBand.isVisible():
self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized())
super(GraphicsView, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.rubberBand.hide()
rect = self.viewport().rect().intersected(self.rubberBand.geometry())
rect_mapped = self.mapToScene(rect).boundingRect()
print(rect_mapped)
super(GraphicsView, self).mouseReleaseEvent(event)
```
在这个示例中,我们除了在 `mousePressEvent` 中增加了一个设置背景颜色的语句外,与前面的示例程序基本相同,只不过这里框选出来的矩形是红色的。
希望这个示例程序对你有所帮助!
阅读全文