通过重写qgraphicitem实现绘制、拖动、缩放、旋转矩形
时间: 2023-10-31 12:05:37 浏览: 114
QGraphicsItem旋转效果实现
4星 · 用户满意度95%
重写QGraphicsItem类可以实现绘制、拖动、缩放和旋转矩形。下面是一个简单的示例代码:
```python
from PyQt5.QtCore import Qt, QRectF
from PyQt5.QtGui import QPen, QBrush, QColor
from PyQt5.QtWidgets import QGraphicsItem
class RectItem(QGraphicsItem):
def __init__(self, x, y, width, height):
super().__init__()
self.rect = QRectF(x, y, width, height)
self.setFlag(QGraphicsItem.ItemIsMovable, True)
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
self.setFlag(QGraphicsItem.ItemIsFocusable, True)
self.setAcceptHoverEvents(True)
self.pen = QPen(Qt.black, 2, Qt.SolidLine)
self.brush = QBrush(QColor(255, 255, 255, 100))
def boundingRect(self):
return self.rect
def paint(self, painter, option, widget=None):
painter.setPen(self.pen)
painter.setBrush(self.brush)
painter.drawRect(self.rect)
def hoverEnterEvent(self, event):
self.pen = QPen(Qt.red, 2, Qt.SolidLine)
self.update()
def hoverLeaveEvent(self, event):
self.pen = QPen(Qt.black, 2, Qt.SolidLine)
self.update()
def mouseMoveEvent(self, event):
super().mouseMoveEvent(event)
self.update()
def mouseReleaseEvent(self, event):
super().mouseReleaseEvent(event)
self.update()
def itemChange(self, change, value):
if change == QGraphicsItem.ItemSelectedChange:
self.pen = QPen(Qt.red, 2, Qt.SolidLine) if value else QPen(Qt.black, 2, Qt.SolidLine)
self.update()
return super().itemChange(change, value)
def rotate(self, angle):
self.setRotation(angle)
self.update()
```
上述代码创建了一个名为RectItem的类,该类继承自QGraphicsItem类。在该类中,我们重写了boundingRect、paint、mouseMoveEvent和mouseReleaseEvent方法。boundingRect方法返回矩形的边界框,paint方法用于绘制矩形,mouseMoveEvent和mouseReleaseEvent方法用于拖动矩形。
除此之外,我们还重写了itemChange方法,该方法用于更新被选择的矩形的颜色。我们还为矩形设置了可拖动、可选择、可发送几何更改和可接受悬停事件的标志。最后,我们定义了一个rotate方法,用于旋转矩形。
阅读全文