Qt:将QGraphicsItem的可移动区域限制在另一个QGraphicsItem C+内+; 我认为我的问题与此类似,但在C++和QLogiStIm里面。

Qt:将QGraphicsItem的可移动区域限制在另一个QGraphicsItem C+内+; 我认为我的问题与此类似,但在C++和QLogiStIm里面。,c++,qt,qgraphicsitem,movable,C++,Qt,Qgraphicsitem,Movable,我想在另一个QGraphicsItem中修复我的对象的可移动区域。如果我想把物体移到外面,我想让它留在里面 也许可以使用setParentItem() 有人知道如何限制QGraphicsItem内的可移动区域吗 是的,你是对的。就像你必须重新实现itemChange一样。从qt文档中 QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == It

我想在另一个QGraphicsItem中修复我的对象的可移动区域。如果我想把物体移到外面,我想让它留在里面

也许可以使用
setParentItem()


有人知道如何限制QGraphicsItem内的可移动区域吗

是的,你是对的。就像你必须重新实现itemChange一样。从qt文档中

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);
}
其中scene()指项目所在的QGraphicscene。如果不使用QGraphics场景,则必须适当设置QRectF(可能来自父项几何体)。

我解决了我的问题

为此,我添加了重新定义如何设置我的
QGraphicsItem
的位置。我的项仅由
boundingRect()
定义,如下所示:

QRectF MyClass::boundingRect() const
{
return QRectF( -_w/2, -_h/2, _w, _h);
}
所以我想让这个
QRectF
留在场景中。 我的项目的位置由该
QRectF
的中心定义。 使用@Salvatore Avanzo建议的Qt文档中的代码,以下是我的代码:

QVariant Aabb::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.x() - _w/2, newPos.y() -     _h/2)||!rect.contains(newPos.x() - _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() + _h/2)||!rect.contains(newPos.x() + _w/2, newPos.y() - _h/2)) 
    {
        // Keep the item inside the scene rect.
        newPos.setX(qMin(rect.right() - _w/2, qMax(newPos.x() , rect.left() + _w/2)));
        newPos.setY(qMin(rect.bottom() - _h/2, qMax(newPos.y() , rect.top() + _h/2)));
        return newPos;
    }


}

return QGraphicsItem::itemChange(change, value);
}

不要忘记设置场景的
QRectF
(参见问题中的注释)。

谢谢。我尝试了你的代码,这将阻止我的
QRectF
从我的移动
QGraphicsItem
在我的场景左侧和顶部。我仍然需要在场景的右侧和底部阻止它(可能使用
boundingRect().bottomRight()
调整代码)。我会试着让你知道。实际上我不知道为什么你的代码在场景的右上角和左上角的底部不起作用…@user2886875:这可能取决于你使用的rect。你应该调试/打印你的实际矩形坐标。是的,我刚刚注意到,如果我的对象走得更远,我的矩形右边的坐标会改变。它是可扩展的。@user2886875您是如何实现父boundingRect的?您的QGraphicItem父项也是QGraphicItem,对吗?非常感谢,这会更好。事实上,我在右下方也有同样的问题。