Search code examples
c++qtqgraphicssceneqgraphicsitem

Restrict movement area of QGraphicsItem inside of polygon area


I am trying to limit the movement of QGraphicsItem inside of a parent object inherited from QGraphicsPathItem that has an arbitrary complex shape (not square).

As I understand, I should extract each point of the moving object and check whether each of them is not contained in the parent QPainterPath. Then split the parent QPainterPath into small rectangle-shaped polygons and restrict movement area in the bounding box of each sub polygon.

So, I would like to know if there are any other options to exist. Thanks.


Solution

  • Maybe you can check on QGraphicsItem move event if it is still inside QGraphicsPathItem.

    The check itself, you can do it with this QGraphicsItem method:

    bool QGraphicsItem::collidesWithItem(const QGraphicsItem * other, Qt::ItemSelectionMode mode = Qt::IntersectsItemShape) const
    

    And to be sure that item is still fully enclosed inside its parent, set the mode to Qt::ContainsItemShape

    If it is false, return QGraphicsItem to its previous position

    EDIT: this check returns if QGraphicsItems shape is inside other QGraphicsItems shape, not its bounding box.