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

相关推荐
·前路漫漫亦灿灿8 分钟前
C++-AVL树
开发语言·c++
手握风云-14 分钟前
JavaEE 初阶第十五期:文件 IO 的 “管道艺术”(上)
java·java-ee
嫩萝卜头儿15 分钟前
AWT 事件监听器深入浅出:Action/Mouse/Key/Window 全解析与实战
java·开发语言·性能优化
Your易元15 分钟前
模式组合应用-适配器模式
java·前端·microsoft
程序员JerrySUN17 分钟前
四级页表通俗讲解与实践(以 64 位 ARM Cortex-A 为例)
java·arm开发·数据库·redis·嵌入式硬件·缓存
代码哲学系21 分钟前
第一阶段:Java基础入门①Java开发环境搭建
java
penngo31 分钟前
Maven/Gradle常用命令
java·gradle·maven
bug攻城狮32 分钟前
IDEA项目名称后面中括号的原因分析和解决方案
java·ide·后端·intellij-idea
种子q_q35 分钟前
在 Java 中isEmpty()、null 、""和isBlank()的区别
java·后端·面试
Vallelonga1 小时前
C++ 中的智能指针
开发语言·c++