【发布时间】:2016-11-02 01:48:09
【问题描述】:
有没有人有更好的方法将QGraphicsItem 的孩子限制在场景中?
我已经通过覆盖 itemChange 成功地将父 QGraphicsItem 约束到其场景,但现在我需要为子 QGraphicsItem 做同样的事情。
示例用例:
此代码在大多数情况下都有效。唯一的问题是QGraphicsItem 撞击任一侧时的速度会影响其终点位置:
QVariant SizeGripItem::HandleItem::itemChange(GraphicsItemChange change,
const QVariant &value)
{
QPointF newPos = value.toPointF();
if (change == ItemPositionChange)
{
if(scene())
{
newPos.setY(pos().y()); // Y-coordinate is constant.
if(scenePos().x() < 0 ) //If child item is off the left side of the scene,
{
if (newPos.x() < pos().x()) // and is trying to move left,
{
newPos.setX(pos().x()); // then hold its position
}
}
else if( scenePos().x() > scene()->sceneRect().right()) //If child item is off the right side of the scene,
{
if (newPos.x() > pos().x()) //and is trying to move right,
{
newPos.setX(pos().x()); // then hold its position
}
}
}
}
return newPos;
}
对于父项,我使用了:
newPos.setX(qMin(scRect.right(), qMax(newPos.x(), scRect.left())));
效果很好,但我不知道如何或是否可以在这里使用它。
【问题讨论】:
-
到场景还是查看?
-
问题在于添加速度的代码,在调用
setPos之前,您应该不需要在itemChange中执行此操作。你能显示那个代码吗? -
我没有那个代码。滑块的移动速度与鼠标拖动它的速度一样快。
标签: c++ qt parent-child qgraphicsscene qgraphicsitem