qgraphicsitem 复制副本_Qt:限制QGraphicsItem在其他QGraphicsItem C ++内部的可移动区域...

I think my question is similar to this post but in C++ and inside a QGraphicsItem.

I would like to fix the movable area of my object inside an other QGraphicsItem. I want my object to stay inside if I try to move it outside.

Maybe the idea will be to use setParentItem().

Does someone know how to restrict a movable area inside a QGraphicsItem please?

解决方案

I solved my problem!

For this I add to redefine how to set the position of my QGraphicsItem. My item is just define by the boundingRect() like this:

QRectF MyClass::boundingRect() const

{

return QRectF( -_w/2, -_h/2, _w, _h);

}

So I wanted this QRectF to stay inside the scene.

The position of my item is define by the center of this QRectF.

Using the code from the Qt documentation proposed by @Salvatore Avanzo here is my code:

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

}

Don't forget to set the QRectF of the scene (see comments in the question).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值