QGraphicsItem的缩放

QGraphicsItem的缩放

QgarphicsItem是Qt视图体系中的项。QGraphicsItem本身是不支持鼠标拖动来缩放的,本文介绍如何通过更改鼠标事件来修改项的大小。(本文所用Qt版本为Qt4.8)

下文代码实现的功能为:按住shift,再用鼠标拖动,可以改变Box的大小。

定义类Box

class Box:public QGraphicsItem
{
    Q_DECLARE_TR_FUNCTIONS(Box)
public:
    Box();

    ...

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
};
Box::Box()
{
    setFlags(QGraphicsItem::ItemIsSelectable|
             QGraphicsItem::ItemIsMovable|
             QGraphicsItem::ItemSendsGeometryChanges|
             QGraphicsItem::ItemIsFocusable);       //接受键盘事件

    mBoundingRect = QRectF(0,0,100,100);
    mBoundingRect.translate(-mBoundingRect.center());
}

上面两段代码为Box类的定义及构造函数的实现,最重要的是三个鼠标函数的重载,及在setFlag中使Box可以接受键盘事件。

重载mousePressEvent

void Box::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if(event->modifiers()&Qt::ShiftModifier)
    {
        resizing = true;             //resizing变量在鼠标点击时变为true                                                    //在放开时变为false
        setCursor(Qt::SizeAllCursor);//鼠标样式变为十字
    }
    else
        QGraphicsItem::mousePressEvent(event);
}

重载mouseMoveEvent

void Box::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if(resizing)
    {
        QRectF rect(mBoundingRect);
        if(event->pos().x()<rect.x())
            rect.setBottomLeft(event->pos());
        else
            rect.setBottomRight(event->pos());
        mBoundingRect=rect;
        mBoundingRect.translate(-mBoundingRect.center());
        scene()->update();
    }
    else
        QGraphicsItem::mouseMoveEvent(event);
}

在这里,简单的更新Box的左下角和右上角来匹配鼠标位置。更好的做法是分别处理x和y坐标。

重载mouseReleaseEvent

void Box::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(resizing)
    {
        resizing = false;
        setCursor(Qt::ArrowCursor);
    }
    else
        QGraphicsItem::mouseReleaseEvent(event);
}

用户在改变大小的过程中放开鼠标,就将resizing改为true,以及将鼠标样式变回箭头。

完整的程序我已上传,请点击这里

版本信息

1.0 20170921

知识共享许可协议
本作品采用知识共享署名-相同方式共享 3.0 未本地化版本许可协议进行许可。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值