0

I have a problem limiting the move of my QGraphicItems:

QVariant CustomRectItem::itemChange(GraphicsItemChange change, const QVariant& value)
{
    if (change == QGraphicsItem::ItemPositionChange && this->scene()) {

        // parameter value is the new position
        QPointF newPos = value.toPointF();
        QRectF rect = this->scene()->sceneRect();

        // keep the item inside the scene rect
        if (!rect.contains(newPos)) {
            if(newPos.x() < rect.x())
                newPos.setX(rect.x());
            return newPos;
        }
    }
    return QGraphicsItem::itemChange(change, value);
}

This code should prevent an item from beeing dragged to the left of the scene and thereby increasing it's size. It kinda works. My problem is:

I insert to items when the scene is created. On sits at x=0 (scene coord.) the other at x=10 (scene coord.) With this code I CAN NOT drag the second item left of x=10.

It seems as if the call to QGraphicsItem::scene() returns different scenes for both items.

HWende
  • 1,705
  • 4
  • 18
  • 30

1 Answers1

0

I've found the answer in this thread: Why does QGraphicsItem::scenePos() keep returning (0,0)

The problem was located in the CREATION of the items. Be careful to NOT position them in the constructor. One must position them after appearing in the scene...

for (int i = 0; i < 3; ++i){
    for (int j = 0; j < 3; ++j){
        item = new CustomRectItem(0, 0, 20, 20);
        item->setFlags(QGraphicsItem::ItemIsMovable |
                       QGraphicsItem::ItemSendsScenePositionChanges);
        scene->addItem(item);
        item->setPos(i*30, j*30);
    }
}
Community
  • 1
  • 1
HWende
  • 1,705
  • 4
  • 18
  • 30