restraining QGraphicsPolygonItem on a QGraphicsScene

  • Hi,

    I am making a tangram puzzle with my son. Tangram puzzle pieces can rotate. Easily done in qt as is moving the pieces around. However, restraining the pieces in the scene is freaking me out. The puzzle piece stays within the bounds of the scene fine if the piece is not rotated. However, when the piece is rotated odd things happen; half the piece goes out of bounds, or the whole piece cannot approach the edge by odd distances. I am freaking out about the math. I have used qDebug to look at the positions, and the piece should behave properly, but it isn't... what am I missing. Here is the itemChanged override->

    QVariant PuzzlePiece::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
        if (change == ItemPositionChange && scene()) {
                QPointF newPos = value.toPointF();
                QRectF rect = scene()->sceneRect();
                QPolygonF poly = mapToScene(tangramShape);
                rect.setWidth(rect.width() - poly.boundingRect().width());
                rect.setHeight(rect.height() - poly.boundingRect().height());
                if (!rect.contains(newPos))
                    qDebug() << newPos << rect << poly.boundingRect();
                    newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
                    newPos.setY(qMin(rect.bottom(), qMax(newPos.y(),;
                    qDebug() << newPos;
                    return newPos;
        return QGraphicsItem::itemChange(change, value);

    Is the mapToScene messing things up? Any help would be appreciated.

    Craig Bakalian

  • setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);

  • setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);

    Is not changing the behavior. I think I may need to just implement a mouse move function.

  • @CraigBakalian
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);

  • all of those flags are set. I still have unusual bounds checking after an object is rotated, even if i get the boundingRect of a polygon. I cannot figure it out.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.