pyqt5 graphicview 点击坐标后,在周围框选一个100*100的红色矩形 完整代码
时间: 2024-02-14 11:05:21 浏览: 69
以下是一个完整的示例代码,实现了在 QGraphicsView 中点击鼠标后在指定位置周围框选一个 100*100 的红色矩形:
```python
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtCore import Qt
class MyGraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.setScene(QGraphicsScene(self))
self.setRenderHint(QPainter.Antialiasing)
self.setRenderHint(QPainter.SmoothPixmapTransform)
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)
self.setOptimizationFlag(QGraphicsView.DontAdjustForAntialiasing, True)
self.setOptimizationFlag(QGraphicsView.DontSavePainterState, True)
self.setOptimizationFlag(QGraphicsView.DontAdjustForDrag, True)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
pos = self.mapToScene(event.pos())
rect = self.scene().addRect(pos.x()-50, pos.y()-50, 100, 100)
rect.setBrush(QBrush(QColor("red")))
rect.setPen(Qt.NoPen)
if __name__ == '__main__':
app = QApplication([])
view = MyGraphicsView()
view.show()
app.exec_()
```
运行以上代码,点击 QGraphicsView 中的任意位置,即可在该位置周围框选一个 100*100 的红色矩形。
阅读全文