Prevent QGraphicsItem from moving outside of QGraphicsScene

前端 未结 3 1505
孤城傲影
孤城傲影 2021-02-07 18:20

I have a scene which has fixed dimensions from (0;0) to (481;270):

scene->setSceneRect(0, 0, 481, 270);

Inside of it, I have a custom

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 18:50

    You can override QGraphicsItem::mouseMoveEvent() like this:

    YourItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
    {
        QGraphicsItem::mouseMoveEvent(event); // move the item...
    
        // ...then check the bounds
        if (x() < 0)
            setPos(0, y());
        else if (x() > 481)
            setPos(481, y());
    
        if (y() < 0)
            setPos(x(), 0);
        else if (y() > 270)
            setPos(x(), 270);
    }
    

提交回复
热议问题