Ways to keep GraphicItems inside GraphicsSceneRect

  • Hello everybody,
    I want to write a desktop application in which I add and edit different items on a QGrapgicsScene. While doing this I want the applicable GraphicsScene Region to be only the GraphicsSceneRect. That means if the user moves an item he/she shall not be able to move the item out of the visible region because items could get lost that way or could only be seen by using scrollbars which I absolutely do not want in my application. The Windowsize of the application and the size of the GrpahicsScene is fixed which might make it more easy to implement. My question is now: Which Qt functions are the best way to implement such boundary which lets no object leave the defined GraphicsSceneRect?
    Thanks for your help!

  • Hi!

    with this:
    @QRectF Scene::visibleRect()
    QPointF tl(this->views().first()->horizontalScrollBar()->value(), this->views().first()->verticalScrollBar()->value());
    QPointF br = tl + this->views().first()->viewport()->rect().bottomRight();
    QMatrix mat = this->views().first()->matrix().inverted();

    return mat.mapRect(QRectF(tl,br));

    You can get visible scene rect.

    Then you can have the check if item is inside the rect.
    Code from one of my projects:
    @ if(( start->pos().y() + start->boundingRect().height() /2) < myScene->visibleRect().top())

    else if((start->pos().y() - start->boundingRect().height() /2) > myScene->visibleRect().bottom())

    else if((start->pos().x() + start->boundingRect().width() /2) > myScene->visibleRect().right())

    else if((start->pos().x() - start->boundingRect().width() /2) < myScene->visibleRect().left())

    This will check every top corner of the graphics item, and if it's outside, it'll center on it.
    You can simply change it and create a bool function ,which return false or true. And based on the returning value, you either break move function, center item etc...

    I didn't find any helpful functions, so wrote my own :) .

    Hope it helps,

  • Hey Jake,
    thanks a lot for your answer. Unfortunately a bunch of other major problems popped up since, so I was not able to implement it yet.
    If there come up more questions to this specific problem, I will post it here.
    Again thanks for your help!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.