Qt World Summit: Submit your Presentation

[SOLVED] Restrict Movement Of GraphicsViewItem To certain area in scene

  • Hello
    My Problem is simple , i cant find a way to restrict the movement of a graphicsviewitem like a Qgraphicsrectitem to an certain area in scence. for example another qgraphicsrectitem which its parent.Help.

    Thank You

  • Take a look at QGraphicsItem::itemChange.
    When you overload it, you can handle the case QGraphicsItem::ItemPositionChange, and override any position changes so they stay within the allowed area.

    This only works if the item itself is moved, not if any of it's parents is moved.

  • @Asperamanca
    i came across this solution... logically this seems right...but its not making any diffrence...shouldnt it restrict the movement to one axis...wats the mistake...am i not set itemIsMovable flag

    QVariant MyItem::itemChange(GraphicsItemChange change, const QVariant &value)
    if (change == ItemPositionChange)
    return QPointF(pos().x(), value.toPointF().y());
    return QGraphicsItem::ItemChange(change, value);

  • First, I would make sure you actually get called. For performance reasons, many types of itemChange first have to be activated by setting flags.
    For this change, you need to activate a flag: ItemSendsPositionChanges (see docs of ItemPositionChange).

  • So I found solution which is easier to implement...
    Instead of item change i overloaded QGraphicsItem::mouseMoveEvent(event)...
    it restricts movement between x1 and x2... and it is restricted to x axis if i set diffrence between y1 and y2 equal to height of item

    void ScheduleScroller::mouseMoveEvent(QGraphicsSceneMouseEvent *event)

       if (x() < x1)
           setPos(x1, y());
       else if (x() + boundingRect().right() > x2)
           setPos(x2 - boundingRect().width(), y());
       if (y() < y1)
           setPos(x(), y1);
       else if ( y()+ boundingRect().bottom() > y2)
           setPos(x(), y2 - boundingRect().height());