PDA

View Full Version : QGraphicsItem Horizontal/Vertical move only



prashant
9th November 2009, 05:34
How do you restrict a QGraphicsItem to move horizontally or vertically?
For example, If an item is at (0,0), how do I restrict the movement between (0,0)-(150,0)?

yogeshgokul
9th November 2009, 06:23
How do you restrict a QGraphicsItem to move horizontally or vertically?
For example, If an item is at (0,0), how do I restrict the movement between (0,0)-(150,0)?
For this you need to subclass QGraphicsScene and re-implement mouseMoveEvent. In mouseMoveEvent, you need to identify that particular item and manually restrict the movable area of that item. Here the point is, the item cannot cannot control this behaviour but its parent can.;)

yonnak
9th November 2009, 10:02
Hello,

You can also reimplement the item itemChange(GraphicsItemChange change, const QVariant &value) fonction. I use this to implement a snap to grid behaviour.

This is an example from the doc that keep item inside scene:



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);
}