ItemChange re-implementation of QGraphicsItem
-
Hello,
I am having some problems with the re-implementation of a subclass of QGraphicsRectItem. My rectangular item is a movable item that gets resized from time to time only in width. The widget it's contained in, has a fixed height so that never changes.
I restrict the item so it can't grow bigger than the bounding rect of the viewport, so it can only move when its smaller and gets space to move.
I re implemented the itemChange(GraphicsItemChange change, const QVariant &value) to restrict the item to not be able to move outside of the viewport either.All this was working fine. I also have a different function which just scales and moves the rectangular item doing:
@
setRect(startPos, 0, dx, rect().height());
@startpos and dx are passed to the function and calculated before. That works as intended and the rectangular item gets its new size and is positioned somewhere within the viewport's x-coor according to startPos.
The problem now is that when that happens, for example if startPos was 10, I cannot move it to the left to position 0 anymore, I can only keep moving it to the right and now the boundingRect to the right edge has grown and the item can move out of the scene by 10. It's like the sceneRect is shifted to start at whatever 'startPos' is. I don't understand why this is happening.
the implementation of the itemChange is this:
@
QVariant MyRect::itemChange(GraphicsItemChange change, const QVariant &value)
{
if(change == ItemPositionChange && scene())
{
QPointF newPos = value.toPointF();
QPointF nPos(newPos.x() + rect().width(), newPos.y() + rect().height());
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; } if(!r.contains(nPos)) { qreal excessX = rect().right() - r.right(); newPos.setX(rect().x() - excessX); newPos.setY(0); return newPos; } } return QGraphicsRectItem::itemChange(change, value);
}
@If I just comment out this method, it's fine except the item moves freely out of the viewport which is what I want to avoid. The problem only arises after I call the function to resize and position the item.
Any ideas?Thanks.