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

相关推荐
xunyan62341 天前
面向对象(上)-封装性的引入
java·开发语言
脸大是真的好~1 天前
黑马JAVAWeb-05 JDBC入门-预编译SQL-Mybatis入门-Mybatis日志输出-数据库连接池-增删改查-XML映射配置
java
还算善良_1 天前
XML签名
xml·java·开发语言
梅梅绵绵冰1 天前
xml方式实现AOP
xml·java·开发语言
桦说编程1 天前
Guava 迭代器增强类介绍
java·后端·设计模式
235161 天前
【JVM】Java为啥能跨平台?JDK/JRE/JVM的关系?
java·开发语言·jvm·spring boot·后端·spring·职场和发展
2401_860319521 天前
【无标题】
开发语言·学习·rust
courtfu1 天前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端
枫子有风1 天前
Go语言流程控制
android·java·golang
小裕哥略帅1 天前
订单管理--实时算出在途数量、收货数量、到货数量、已发货数量和未发货数量
java·开发语言