Restricting a movable QGraphicsRectItem in the Scene Rect
-
Hi,
I have a subclass of QGraphicsRectItem that is basically a rectangle that is user-movable and gets resized automatically by the application when needed.
The rectangle starts out being the same size of the whole view, but when it shrinks (only horizontally) it has space to move and it moves fine. What I am trying to do is keep the item inside the scene rectangle. The scene rectangle is always the same size as the view's viewport so basically I am trying to be able to move the rectangle freely but if one of the sides hits the viewport's wall it should not be able to move further, as to never lose sight of a piece of the rectangle item. Also stop the rectangle from growing bigger than the viewport's bounding rectangle so that when the rect item covers the whole viewport it cannot be moved.
For this I found in the docs the way to do it is re-implementing QGraphicsRectItem::itemChange() in my class. So I did:
@
QVariant ReferenceRect::itemChange(GraphicsItemChange change, const QVariant &value)
{
if(change == ItemPositionChange && scene())
{
QPointF newPos = value.toPointF();
QRectF r = scene()->sceneRect();if(!r.contains(newPos)) { newPos.setX(qMin(r.right(), qMax(newPos.x(), r.left()))); newPos.setY(qMin(r.bottom(), qMax(newPos.y(), r.top()))); return newPos; } } return QGraphicsRectItem::itemChange(change, value);
}
@This does the job fine for the left hand boundaries and for the top boundaries, but I can still move the rectangle out of view to the right.
So how could I restrict this to also the left hand boundary? Also I'm wondering, above the newPos of my Rect item, is it the top left-corner of the rectangle??
I appreciate any tips, tricks or info of any kind!
Thanks. -
[quote author="xtraction" date="1322238215"] yes thanks!, just added another 'if' with another point nPos taking into account the size of the rectangle and did the same thing and it works fine.
@
QPointF nPos(newPos.x() + rect().width(), newPos.y() + rect().height());
@
[/quote]Hi xtraction!
Can you share your code of QgraphicsItem? I tried to use the same code but i dont know why i can still move the rectangle out of the scene. Thanks! -
I fixed it. So don't need your code anymore.:)
-
Can anyone please share code for custom QgraphicsItem.
right now i am facing same issue "QGraphicsItem is moving out of scene" when i am doing mouse move for graphics item