QGraphicsItem限制拖动方向和位置

本文介绍如何在Qt中使用QGraphicsItem时,通过重载itemChange()函数来限制图形的拖动方向,例如仅允许水平或垂直拖动,这对于创建特定的图形界面非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用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);
}

 

可以通过重载 QGraphicsItem 的 `mouseMoveEvent` 函数来实现只沿着 X 轴拖动图形的功能。 下面是一个简单的实现示例: ```cpp class MyItem : public QGraphicsItem { public: MyItem(QGraphicsItem *parent = nullptr) : QGraphicsItem(parent) { // 设置图形的初始位置大小 setPos(0, 0); m_width = 100; m_height = 100; } QRectF boundingRect() const override { return QRectF(0, 0, m_width, m_height); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override { // 绘制图形 painter->drawRect(boundingRect()); } void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override { // 获取当前鼠标位置上一次鼠标位置之间的差值 QPointF delta = event->pos() - event->lastPos(); // 只允许沿着 X 轴方向移动图形 QPointF newPos = pos() + QPointF(delta.x(), 0); // 限制图形的移动范围 if (newPos.x() < 0) newPos.setX(0); if (newPos.x() + m_width > scene()->width()) newPos.setX(scene()->width() - m_width); // 更新图形的位置 setPos(newPos); } private: qreal m_width; qreal m_height; }; ``` 在上面的示例中,我们重载了 `mouseMoveEvent` 函数,并在其中实现了只沿着 X 轴方向拖动图形的逻辑。具体来说,当鼠标拖动图形时,我们计算出当前鼠标位置上一次鼠标位置之间的差值,并将其加到图形的当前位置上,从而实现了图形的移动。同时,我们还限制了图形的移动范围,使其不能超出场景的边界。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值