Qt: limit the moved area of ​​QGraphicsItem inside another QGraphicsItem C ++

I think my question is similar to this post , but in C ++ and inside QGraphicsItem.

I would like to lock the moving area of ​​my object inside another QGraphicsItem object. I want my object to stay inside if I try to move it outside.

Maybe the idea would be to use setParentItem() .

Does anyone know how to limit the moveable area inside QGraphicsItem, please?

+1
source share
2 answers

I solved my problem!

For this, I add to override how to set the position of my QGraphicsItem . My element is simply defined by boundingRect() as follows:

 QRectF MyClass::boundingRect() const { return QRectF( -_w/2, -_h/2, _w, _h); } 

So I wanted this QRectF stay inside the scene. The position of my object is determined by the center of this QRectF . Using the code from the Qt documentation suggested by @Salvatore Avanzo, here is my code:

 QVariant Aabb::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == ItemPositionChange && scene()) { // value is the new position. QPointF newPos = value.toPointF(); QRectF rect = scene()->sceneRect(); if (!rect.contains(newPos.x() - _w/2, newPos.y() - _h/2)||!rect.contains(newPos.x() - _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() - _h/2)) { // Keep the item inside the scene rect. newPos.setX(qMin(rect.right() - _w/2, qMax(newPos.x() , rect.left() + _w/2))); newPos.setY(qMin(rect.bottom() - _h/2, qMax(newPos.y() , rect.top() + _h/2))); return newPos; } } return QGraphicsItem::itemChange(change, value); } 

Remember to set the QRectF scene (see comments in the question).

+2
source

Yes you are right. As in here , you need to override itemChange. From qt documentation

 QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == ItemPositionChange && scene()) { // value is the new position. QPointF newPos = value.toPointF(); QRectF rect = scene()->sceneRect(); if (!rect.contains(newPos)) { // Keep the item inside the scene rect. newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left()))); newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top()))); return newPos; } } return QGraphicsItem::itemChange(change, value); } 

where scene () refers to the QGraphicsScene in which the item is located. If you are not using QGraphicScene, you should set QRectF accordingly (possibly from the geometry of the parent element).

+4
source

All Articles