Prevent QGraphicsItem from moving outside of QGraphicsScene

前端 未结 3 1525
孤城傲影
孤城傲影 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
    2021-02-07 18:37

    This code keeps your complete item in scene. Not only the upper left pixel of your item.

    void YourItem::mouseMoveEvent( QGraphicsSceneMouseEvent *event )
    {
        QGraphicsItem::mouseMoveEvent(event); 
    
        if (x() < 0)
        {
            setPos(0, y());
        }
        else if (x() + boundingRect().right() > scene()->width())
        {
            setPos(scene()->width() - boundingRect().width(), y());
        }
    
        if (y() < 0)
        {
            setPos(x(), 0);
        }
        else if ( y()+ boundingRect().bottom() > scene()->height())
        {
            setPos(x(), scene()->height() - boundingRect().height());
        }
    }
    

提交回复
热议问题