pyqt5如何画可拖动改变大小,可旋转的矩形,代码实现
时间: 2024-05-12 20:17:42 浏览: 20
可以使用QGraphicsRectItem来实现可拖动改变大小、可旋转的矩形,例如:
```python
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsRectItem, QApplication
from PyQt5.QtGui import QBrush, QPen, QPainter
from PyQt5.QtCore import QPointF
class RotatableRectItem(QGraphicsRectItem):
def __init__(self, rect):
super().__init__(rect)
self.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemSendsGeometryChanges)
self.brush = QBrush(QColor(255, 255, 255, 50))
self.pen = QPen(QColor(0, 0, 0, 255))
self.pen.setWidth(2)
self.center = QPointF(self.boundingRect().center())
def paint(self, painter, option, widget):
painter.setPen(self.pen)
painter.setBrush(self.brush)
painter.drawRect(self.rect())
def boundingRect(self):
return super().boundingRect().adjusted(-2, -2, 2, 2)
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange:
self.center = QPointF(value.x() + self.boundingRect().width() / 2,
value.y() + self.boundingRect().height() / 2)
if change == QGraphicsItem.ItemRotationChange:
self.setRotation(value)
return super().itemChange(change, value)
```
我们可以在QGraphicsScene中添加该矩形:
```python
class MyScene(QGraphicsScene):
def __init__(self):
super().__init__()
self.rect = RotatableRectItem(QRectF(0, 0, 100, 100))
self.addItem(self.rect)
```
最后在QGraphicsView中显示该场景:
```python
if __name__ == '__main__':
app = QApplication([])
view = QGraphicsView()
scene = MyScene()
view.setScene(scene)
view.show()
app.exec()
```
这样就可以展现一个可拖动改变大小、可旋转的矩形。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)
![](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)
![](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)