我认为我的问题类似于post,但在C++中和QGraphicsItem中。
我想将对象的可移动区域固定在另一个QGraphicsItem中。如果我尝试将其移到外部,我希望将其留在内部。
可能的想法是使用setParentItem()
。
有人知道如何限制QGraphicsItem内部的可移动区域吗?
最佳答案
是的,你是对的。与here中一样,您必须重新实现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()指该项目所在的QGraphicsScene。如果不使用QGraphicScene,则必须适当设置QRectF(可能来自父项几何)。
关于c++ - Qt:在另一个QGraphicsItem C++中限制QGraphicsItem的可移动区域,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22512602/