pyqt5如何画任意形状的矩形,可拖动改变大小,可旋转
时间: 2024-05-06 15:21:19 浏览: 91
可以使用QGraphicsItem实现。具体操作流程可以参考以下代码:
```python
from PyQt5.QtCore import QPointF, QRectF, Qt
from PyQt5.QtGui import QBrush, QColor, QPainter, QPen
from PyQt5.QtWidgets import QApplication, QGraphicsItem, QGraphicsScene, QGraphicsView
class RectItem(QGraphicsItem):
def __init__(self, rect, parent=None):
super().__init__(parent)
self.rect = rect
self.setFlags(QGraphicsItem.ItemIsMovable |
QGraphicsItem.ItemIsSelectable |
QGraphicsItem.ItemSendsGeometryChanges)
self.setAcceptHoverEvents(True)
self.setCursor(Qt.SizeAllCursor)
def boundingRect(self):
return self.rect.normalized()
def paint(self, painter, option, widget):
pen = QPen(QColor(0, 0, 255), 2, Qt.SolidLine)
brush = QBrush(QColor(255, 255, 255, 128), Qt.SolidPattern)
painter.setPen(pen)
painter.setBrush(brush)
painter.drawRect(self.rect)
def hoverMoveEvent(self, event):
rect = self.rect.adjusted(7, 7, -7, -7)
if rect.contains(event.pos()):
self.setCursor(Qt.SizeAllCursor)
else:
self.setCursor(Qt.ArrowCursor)
def mousePressEvent(self, event):
self.mouse_pos = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
dx = event.pos().x() - self.mouse_pos.x()
dy = event.pos().y() - self.mouse_pos.y()
self.mouse_pos = event.pos()
self.rect.translate(dx, dy)
self.update()
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange:
self.scene().update()
return super().itemChange(change, value)
class GraphicsScene(QGraphicsScene):
def __init__(self, rect):
super().__init__()
self.rect_item = RectItem(rect)
self.addItem(self.rect_item)
if __name__ == '__main__':
rect = QRectF(50, 50, 100, 80)
app = QApplication([])
view = QGraphicsView()
view.setRenderHints(QPainter.Antialiasing |
QPainter.SmoothPixmapTransform)
scene = GraphicsScene(rect)
scene.setSceneRect(0, 0, 300, 200)
view.setScene(scene)
view.show()
app.exec_()
```
该代码演示了如何使用QGraphicsItem绘制可移动、可缩放、可旋转的矩形。
阅读全文