QGraphicsItem限制拖动方向和位置

在使用QGraphicsItem绘制图形时,有时候需要限制拖动方式,如只能水平拖动或者只能垂直拖动。查找了一些资料,具体出处也不记得了,找到利用itemChange()函数限制移动位置的方法。

首先,继承要绘制的QGraphicsItem类,实现自己的类。设置flag如下:

setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable|QGraphicsItem::ItemSendsGeometryChanges);

//QGraphicsItem::ItemIsSelectable表示item可选中

//QGraphicsItem::ItemIsMovable表示Item可移动

//QGraphicsItem::ItemSendsGeometryChanges使itemChange()函数有效。

其次,重载itemChange()函数。其中rect用来限制移动范围,高度设置为0则只能水平移动,宽度设置为0则只能垂直移动。

QVariant MyRectItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && scene())
    {
        QPointF newPos = value.toPointF();
        QRectF rect(0, this->pos().y(), scene()->width(), 0); //水平移动
        //QRectF rect(0, 0, 0, scene()->height()); //垂直移动
        //QRectF rect(0, this->pos().x(), scene()->width(), 0); //向右下方移动
        //QRectF rect(0, -this->pos().x(), scene()->width(), 0); //向右上方移动
        if (!rect.contains(newPos))
        {
            newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
            newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
            return newPos;
        }
    }
    return QGraphicsRectItem::itemChange(change, value);
}

 

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
在Qt中,可以通过重写`QGraphicsItem`的`boundingRect()`函数来限制`QGraphicsItem`的移动范围。`boundingRect()`函数返回一个矩形区域,表示`QGraphicsItem`的边界。 以下是一种常见的实现方式: 1. 在自定义的`QGraphicsItem`子类中,重写`boundingRect()`函数,返回一个限制移动范围的矩形区域。例如,可以使用`QRectF`类来定义一个矩形区域,并设置其左上角和右下角的坐标。 ```cpp QRectF CustomItem::boundingRect() const { // 设置移动范围为(0, 0)到(100, 100) return QRectF(0, 0, 100, 100); } ``` 2. 在重写`boundingRect()`函数时,还可以考虑当前场景中其他`QGraphicsItem`的位置和大小,以便更精确地限制移动范围。 3. 如果需要在限制移动范围时保持`QGraphicsItem`的位置不变,可以在重写`itemChange()`函数时处理位置变化。例如,可以在`itemChange()`函数中判断新的位置是否超出了限制范围,并将其调整回合法的位置。 ```cpp QVariant CustomItem::itemChange(GraphicsItemChange change, const QVariant& value) { if (change == ItemPositionChange && scene()) { // 获取新的位置 QPointF newPos = value.toPointF(); // 判断新的位置是否超出了限制范围 QRectF boundingRect = this->boundingRect(); if (!boundingRect.contains(newPos)) { // 调整位置到合法范围内 newPos.setX(qMin(boundingRect.right(), qMax(newPos.x(), boundingRect.left()))); newPos.setY(qMin(boundingRect.bottom(), qMax(newPos.y(), boundingRect.top()))); return newPos; } } return QGraphicsItem::itemChange(change, value); } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值