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的博客

相关推荐
鄃鳕5 分钟前
python迭代器解包【python】
开发语言·python
new coder6 分钟前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
驰羽12 分钟前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
Narcissiffo21 分钟前
【C语言】str系列函数
c语言·开发语言
楚韵天工22 分钟前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
helloworddm23 分钟前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
workflower25 分钟前
软件工程与计算机科学的关系
开发语言·软件工程·团队开发·需求分析·个人开发·结对编程
失散1327 分钟前
分布式专题——43 ElasticSearch概述
java·分布式·elasticsearch·架构
ajsbxi27 分钟前
【Java 基础】核心知识点梳理
java·开发语言·笔记
阿珊和她的猫39 分钟前
深入理解与手写发布订阅模式
开发语言·前端·javascript·vue.js·ecmascript·状态模式