Qt:限制QGraphicsItem在其他QGraphicsItem C ++内部的可移动区域 [英] Qt: restrict movable area of a QGraphicsItem inside an other QGraphicsItem C++

查看:1511
本文介绍了Qt:限制QGraphicsItem在其他QGraphicsItem C ++内部的可移动区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我的问题类似于此帖子,但在C ++中, QGraphicsItem。

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

我想修复我的对象的移动区域在其他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.

也许这个想法是使用 setParentItem()

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

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

推荐答案

我解决了我的问题!

重新定义如何设置我的 QGraphicsItem 的位置。我的项目只是由 boundingRect()定义如下:

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

所以我想要这个 QRectF 留在场景内。
我的项目的位置由 QRectF 的中心定义。
使用@Salvatore Avanzo提出的Qt文档的代码这里是我的代码:

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

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

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

这篇关于Qt:限制QGraphicsItem在其他QGraphicsItem C ++内部的可移动区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆