I want to allow a QGraphicsItem
to be dragged only in certain directions, such as +/-45 degrees, horizontally or vertically, and to be able to "jump" to a new direction once the cursor is dragged far enough away from the current closest direction. This would replicate behaviour in e.g. Inkscape when drawing a straight line and holding Ctrl
(see e.g. this video), but I am unsure how to implement it.
I've implemented a drag handler that grabs the new position of the item as it is moved:
class Circle(QGraphicsEllipseItem):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Flags to allow dragging and tracking of dragging.
self.setFlag(self.ItemSendsGeometryChanges)
self.setFlag(self.ItemIsMovable)
self.setFlag(self.ItemIsSelectable)
def itemChange(self, change, value):
if change == self.ItemPositionChange and self.isSelected():
# do something...
# Return the new position to parent to have this item move there.
return super().itemChange(change, value)
Since the position returned to the parent by this method is used to update the position of the item in the scene, I expect that I can modify this QPointF
to limit it to one axis, but I am unsure how to do so in a way that lets the line "jump" to another direction once the cursor is dragged far enough. Are there any "standard algorithms" for this sort of behaviour? Or perhaps some built-in Qt code that can do this for me?