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

相关推荐
rannn_1114 小时前
【力扣hot100】链表专题|160、206、234、141、142
java·算法·leetcode·链表·面试·开发
leisoo80974 小时前
100GBA股股票数据怎么存ClickHouseRedisMySQLJSON完整对比
大数据·linux·服务器·开发语言·python
不会代码的小猴5 小时前
21. 泛型编程上
开发语言·c++·笔记·算法
IKUN家族6 小时前
Spring IoC&DI
java·spring·rpc
一只旭宝6 小时前
细讲C加加【9】C++ std::function与std::bind详解|仿函数、绑定器、类成员绑定、占位符、成员偏移指针
开发语言·c++·算法
山荷枝7 小时前
03-框架--Spring
java·后端·spring
ChaHae-In7 小时前
SpringBoot统一功能处理
java·spring boot·后端
coder!mq8 小时前
说几个常见的语法糖?
java·开发语言·算法
gugucoding8 小时前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言
Lhan.zzZ8 小时前
在 Visual Studio 2022 中打造可扩展的动态链接库模块:从零搭建到原理解析
开发语言·c++·visual studio