pyqt5如何在label中实现可用鼠标改变大小,可旋转的矩形,代码实现
时间: 2024-05-05 18:19:01 浏览: 88
鼠标移动旋转矩形代码
可以使用QGraphicsView、QGraphicsScene和QGraphicsItem来实现可用鼠标改变大小、可旋转的矩形。以下是代码示例:
```
import sys
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem
from PyQt5.QtGui import QBrush, QPen, QColor
from PyQt5.QtCore import Qt
class GraphicsRectItem(QGraphicsRectItem):
def __init__(self, *args, **kwargs):
super(GraphicsRectItem, self).__init__(*args, **kwargs)
self.setFlag(QGraphicsItem.ItemIsMovable, True)
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.setFlag(QGraphicsItem.ItemIsFocusable, True)
self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
self.setAcceptHoverEvents(True)
self.setCursor(Qt.SizeFDiagCursor)
self.setBrush(QBrush(QColor(255, 255, 255, 127)))
self.setPen(QPen(Qt.black, 1, Qt.SolidLine))
self.setZValue(1)
def hoverMoveEvent(self, event):
if self.isSelected():
self.setCursor(Qt.SizeFDiagCursor)
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange:
self.scene().update()
elif change == QGraphicsItem.ItemSelectedChange:
self.setCursor(Qt.SizeFDiagCursor if value else Qt.ArrowCursor)
return super(GraphicsRectItem, self).itemChange(change, value)
def paint(self, painter, option, widget):
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(self.pen())
painter.setBrush(self.brush())
painter.drawRect(self.rect())
def boundingRect(self):
return self.rect().adjusted(-4, -4, 4, 4)
def shape(self):
return QGraphicsRectItem.shape(self)
class GraphicsView(QGraphicsView):
def __init__(self, *args, **kwargs):
super(GraphicsView, self).__init__(*args, **kwargs)
def wheelEvent(self, event):
if event.orientation() == Qt.Vertical:
factor = 1.1 if event.angleDelta().y() > 0 else 0.9
self.scale(factor, factor)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Delete:
for item in self.scene().selectedItems():
self.scene().removeItem(item)
else:
super(GraphicsView, self).keyPressEvent(event)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = GraphicsView()
scene = QGraphicsScene(view)
view.setScene(scene)
rect = GraphicsRectItem(0, 0, 100, 100)
scene.addItem(rect)
view.show()
sys.exit(app.exec_())
```
在这个示例中,我们创建了一个名为GraphicsRectItem的类,该类继承自QGraphicsRectItem,并重写了一些方法来实现可用鼠标改变大小、旋转的矩形。然后,我们创建一个名为GraphicsView的类,该类继承自QGraphicsView,并重写了一些方法来实现鼠标滚轮缩放、按键删除等功能。最后,我们在主函数中创建视图、场景和矩形对象,并将矩形添加到场景中。
阅读全文