Qt限制QGraphicsScene QGraphicsItem内部的移动范围

用过QGraphicsView的都知道,原点一般设定在view和item的中心,所以帮助文档和这个网友说的不一定跟我们对的上:

关于Qt限制QGraphicsScene内部Item的移动范围_qgraphicsitem限制移动范围-CSDN博客

首先,设定view的scenerect:

复制代码
ui->graphicsView->setScene(scene);
ui->graphicsView->setSceneRect(-ui->graphicsView->width()/2,-ui->graphicsView->height()/2,ui->graphicsView->width(),ui->graphicsView->height());

然后我们的item也是中心为原点:

cpp 复制代码
QRectF MyRect::boundingRect()const
{
    return QRectF(-100,-100,200,200);
}

所以最后我们的限定位置为view的scenerect区域:

cpp 复制代码
QVariant MyRect::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && scene())
    {
        QPointF newPos = value.toPointF();//即将要移动的位置scene()->width()
        auto rect = scene()->views().value(0)->sceneRect();
        auto vrect = rect;
        // 由于矩形原点在中心,所以剪掉上下左右距离来判断
        rect.setRect(vrect.x()+boundingRect().width()/2,
                     vrect.y()+boundingRect().height()/2,
                     vrect.width()-boundingRect().width(),
                     vrect.height()-boundingRect().height());


        // 是否在区域内
        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 QGraphicsItem::itemChange(change, value);
}

看图片:

那么,view的sceneRect和scene的sceneRect分别什么意思呢?

中文解析下:

Qt限制QGraphicsScene QGraphicsItem内部的移动范围-3YL的博客

相关推荐
坐吃山猪2 分钟前
Electron04-系统通知小闹钟
开发语言·javascript·ecmascript
翔云 OCR API2 分钟前
护照NFC识读鉴伪接口集成-让身份核验更加智能与高效
开发语言·人工智能·python·计算机视觉·ocr
程序喵大人11 分钟前
CMake入门教程
开发语言·c++·cmake·cmake入门
老华带你飞16 分钟前
房屋租赁管理|基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·毕设
半生过往28 分钟前
前端运行PHP 快速上手 使用 PHPStudy Pro 详细搭建与使用指南
开发语言·前端·php
zlpzlpzyd30 分钟前
ecmascript中Promise和async/await的区别
开发语言·前端·ecmascript
凛_Lin~~37 分钟前
安卓 Java线程八股文 (线程、多线程、线程池、线程安全)
android·java·开发语言
C语言不精41 分钟前
c语言-优雅的多级菜单设计与实现
c语言·开发语言·算法
geekmice41 分钟前
thymeleaf处理参数传递问题
开发语言·lua
哈哈哈笑什么42 分钟前
企业级CompletableFuture并行化完整方案,接口从10s到100ms
java·后端·spring cloud