ayanda83
19th April 2015, 08:49
hi guys, I have a graphicsItem that is a child item of another graphicsItem which is basically a filled rectangle. the child item is movable and I want to limit the movement of the child item to the bounds of the parent item. The bounding rect of the parent is the same size as the scene rect hence I used the scene rect to define the bounds in the code below. But my code below doesn't work and the child item still goes upside the parent item bounds when you drag move it. I want the item to stop at the scene bounds or the parent item bounds (which are the same rect size). please see code below.
QVariant Picture::itemChange(QGraphicsItem::GraphicsItemCha nge change, const QVariant &value)
{
if(change == ItemPositionChange && scene()){
QPointF newPos = value.toPointF();
QRectF rect2 = scene()->sceneRect();
if(!rect2.contains(newPos)){
// Keep the item inside the scene rect.
newPos.setX(qMin(rect2.right(), qMax(newPos.x(), rect2.left())));
newPos.setY(qMin(rect2.bottom(), qMax(newPos.y(), rect2.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
thanking you in advance.
QVariant Picture::itemChange(QGraphicsItem::GraphicsItemCha nge change, const QVariant &value)
{
if(change == ItemPositionChange && scene()){
QPointF newPos = value.toPointF();
QRectF rect2 = scene()->sceneRect();
if(!rect2.contains(newPos)){
// Keep the item inside the scene rect.
newPos.setX(qMin(rect2.right(), qMax(newPos.x(), rect2.left())));
newPos.setY(qMin(rect2.bottom(), qMax(newPos.y(), rect2.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
thanking you in advance.