簡體   English   中英

防止QGraphicsItem移出QGraphicsScene

[英]Prevent QGraphicsItem from moving outside of QGraphicsScene

我有一個固定尺寸從(0; 0)到(481; 270)的場景:

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

在它內部,我有一個自定義GraphicsItem ,我可以移動它,因為標志ItemisMovable ,但我希望它保持在場景內; 我的意思是我不希望它的坐標既不在(0; 0)之下也不在(481; 270)之下。

我嘗試了幾個解決方案,比如重寫QGraphicsItem::itemChange()甚至QGraphicsItem::mouseMoveEvent()但我仍然無法達到我想要的目標。

什么是適合我需求的解決方案? 我是否嚴重使用QGraphicsItem::itemChange()

提前致謝。

您可以像這樣覆蓋QGraphicsItem::mouseMoveEvent()

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

此代碼將您的完整項目保留在場景中。 不僅是項目的左上角像素。

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

警告:建議的解決方案不適用於多個選定項目。 問題是,在這種情況下,只有一個項目接收鼠標移動事件。

實際上, QGraphicsItem上Qt文檔提供了一個示例,它可以准確地解決限制項目移動到場景rect的問題:

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

注意I:您必須啟用QGraphicsItem::ItemSendsScenePositionChanges標志:

item->setFlags(QGraphicsItem::ItemIsMovable
               | QGraphicsItem::ItemIsSelectable
               | QGraphicsItem::ItemSendsScenePositionChanges);

注意II:如果您只想對完成的移動作出反應,請考慮使用GraphicsItemChange標志ItemPositionHasChanged

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM