79166165

Date: 2024-11-07 11:13:09
Score: 0.5
Natty:
Report link

By reimplementing the mouseMoveEvent method, items can be easily restricted from leaving the sceneRect:

def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):

    # 1. Finding the maximum movements that can be made before leaving the scene's
    # bounding rectangle:
    rect = self.mapRectToScene(self.boundingRect())
    max_left_move = self.scene().sceneRect().left() - min(rect.left(), rect.right())
    max_right_move = self.scene().sceneRect().right() - max(rect.left(), rect.right())
    max_up_move = self.scene().sceneRect().top() - min(rect.top(), rect.bottom())
    max_down_move = self.scene().sceneRect().bottom() - max(rect.top(), rect.bottom())
    
    # 2. Calculating the initial vector of movement
    move = event.pos() - event.buttonDownPos(Qt.LeftButton)
    
    # 3. Correcting the movement vector if it causes the item to leave the area:
    move.setX(np.clip(move.x(), max_left_move, max_right_move))
    move.setY(np.clip(move.y(), max_up_move, max_down_move))
    
    # 4. Moving the item
    self.moveBy(move.x(), move.y())

Since I needed to restrict items with transformations, the method that @musicamante offered was not appropriate for my purpose.

Reasons:
  • Blacklisted phrase (0.5): I need
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @musicamante
  • Low reputation (0.5):
Posted by: Kamin