I'm trying to create a minimal QGraphicsItem that acts as a resizer to its parent. I think I'm nearly there but am drawing a blank and how to convey its position to the parent item when it is being moved. What I am going for looks something like this (without the text):
And here is a self contained example of what I have so far:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Resizer(QGraphicsEllipseItem):
def __init__(self, rect=QRectF(0, 0, 10, 10), parent=None, scene=None):
super().__init__(rect, parent, scene)
self.setFlag(QGraphicsItem.ItemIsMovable, True)
def mousePressEvent(self, mouseEvent):
self.resize = True
self.initialPos = self.scenePos()
self.setSelected(True)
def mouseMoveEvent(self, mouseEvent):
if self.resize:
self.currentPos = self.scenePos()
self.change = self.initialPos - self.currentPos
super().mouseMoveEvent(mouseEvent)
def mouseReleaseEvent(self, mouseEvent):
self.resize = False
self.setSelected(False)
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QGraphicsView()
scene = QGraphicsScene()
scene.setSceneRect(0, 0, 500, 500)
view.setScene(scene)
rect = QRectF(100, 100, 150, 50)
box = QGraphicsRectItem(rect)
scene.addItem(box)
resizer = Resizer(parent=box)
resizerWidth = resizer.rect().width() / 2
resizerOffset = QPointF(resizerWidth, resizerWidth)
resizer.setPos(box.rect().bottomRight() - resizerOffset)
view.show()
sys.exit(app.exec_())
So how can I convey self.change
in the mouseMoveEvent
to the parent in a way that the parent is resized as the Resizer
is being moved? Any other suggestions are welcome.
I've tried converting the Resizer
to a subclass of QGraphicsObject
so that it could emit a signal on mouseMoveEvent
, but QGraphicsObject
does not have a paint method and I am unsure on how to display the Resizer
on the scene.
Any advice on this is welcome.