pyqt5 graphicview 点击坐标后,在周围框选一个100*100的红色矩形 完整代码
时间: 2024-02-14 13:05:21 浏览: 48
以下是一个完整的示例代码,实现了在 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 的红色矩形。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)