zoukankan      html  css  js  c++  java
  • QT——在QGraphicsScene中限制图元的拖动范围

    欲使QGraphicsItem可拖动,则需设置标志位:setFlag(ItemIsMovable,true);

    而如果想限制QGraphicsItem对象的移动范围,需要继承QGraphicsItem类,重载itemChange()虚函数,关于该函数的重载,QT文档中示例如下:

    QVariant Component::itemChange(GraphicsItemChange change, const QVariant &value)
    {
        if (change == ItemPositionChange && scene()) {
            // value is the new position.
            QPointF newPos = value.toPointF();
            QRectF rect = scene()->sceneRect();
            if (!rect.contains(newPos)) {
                // Keep the item inside the scene rect.
                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);
    }

    ItemPositionChange 用于通知所属QGraphicsItem的位置即将发生变化,而value的值即为QGraphicsItem将来的位置坐标,以上代码把item将来的位置坐标value与scene rect 的上下左右边界进行比较,根据比较结果更改value,使其取值在scene rect 范围内, 进而达到了限制item拖动范围的目的。

    但上述代码只有在QGraphicsScene的大小已经被事先设定好了才好用,如果预先未设置QGraphicsScene大小,那么scene的大小将随着item的添加不断增大,这种范围的限制就没什么意义了。

    如果我们即想将scene设为自动无限增大的,又想限制item在某方向的拖动,只要找到限制拖动的那条基准线的横坐标或者纵坐标,按照与上述代码中同样的原理,就可轻松限制item的拖动,甚至可以使item按照指定路线被拖动。

  • 相关阅读:
    leetcode第四题
    解决Hystrix主线程结束,子线程拿不到request
    RabbitMQ如何保证消息的顺序性+解决消息积压+设计消息队列中间件
    RabbitMQ 如何保证消息不丢失?
    redis布隆过滤器的使用
    PageHelper自定义count
    mysqlbinlog 工具分析binlog日志
    linuxubuntu常用命令
    MySQL 常用命令
    Ubuntu 16.04 安装 Apache, MySQL, PHP7
  • 原文地址:https://www.cnblogs.com/sfy5848/p/6611824.html
Copyright © 2011-2022 走看看