【问题标题】:Qt moving an Object in a specific RegionQt 在特定区域中移动对象
【发布时间】:2014-05-08 16:53:23
【问题描述】:

我是 Qt 编程新手。到目前为止,我做了一个QGraphicsScene 绘制了一些矩形(看起来像棋盘),然后在场景中添加了一个自己的QGraphicsItem。对于这个项目,我设置了ItemIsMovable 标志。现在我可以移动它,但我想将移动限制在棋盘所在的区域。

我是否必须取消设置标志并手动实现移动,或者是否有一个选项或标志,我可以在其中指定可以移动的区域?

renderableObject::renderableObject(QObject */*parent*/)
{
    pressed = false;
    setFlag(ItemIsMovable);
}

【问题讨论】:

    标签: c++ qt qgraphicsview qgraphicsitem


    【解决方案1】:

    如果要限制可移动区域,可以重新实现QGraphicsItemitemChange()。重新定位项目将导致itemChange 被调用。您应该注意,需要ItemSendsGeometryChanges 标志来捕获QGraphicsItem 的位置变化。

    class MyItem : public QGraphicsRectItem
    {
    public:
        MyItem(const QRectF & rect, QGraphicsItem * parent = 0);
    protected:
        virtual QVariant    itemChange ( GraphicsItemChange change, const QVariant & value );
    };
    
    
    MyItem::MyItem(const QRectF & rect, QGraphicsItem * parent )
        :QGraphicsRectItem(rect,parent)
    {
        setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges);
    }
    
    QVariant MyItem::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);
    }
    

    这将使项目移动仅限于场景矩形。如果你愿意,你可以定义任意的矩形。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 2013-01-31
      相关资源
      最近更新 更多