【问题标题】:How do you change the position of the boundingRect() of a QGraphicsItem on a QGraphicsScene?如何在 QGraphicsScene 上更改 QGraphicsItem 的 boundingRect() 的位置?
【发布时间】:2016-04-09 05:14:46
【问题描述】:

我已将我的QGraphicsItemboundingRect() 设置为场景中的某个坐标。如何根据QGraphicsItem::mouseMoveEvent更改坐标?


下面是我写的代码。但是这段代码仅将我在boundingRect() 中绘制的形状的位置设置为boundingRect() 中的坐标。我想要做的是将整个QGraphicsItem 移动到一个设定的坐标。

void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsItem::mouseMoveEvent(event);

    if (y()>=394 && y()<425) //if in the range between 425 and 394 I want it to move to 440.
    {
        setPos(440, y());
    }
    else if ... //Other ranges such as that in the first if statement
    {
        ... //another y coordinate
    }
    else //If the item is not in any of the previous ranges it's y coordinate is set to 0
    {
        setPos(0,y()); //I had expected the item to go to y = 0 on the scene not the boundingRect()
    }

}

场景是 880 x 860,boundingRect() 设置如下:

QRectF QGraphicsItem::boundingRect() const
{
    return QRectF(780,425,60,30);
}

【问题讨论】:

    标签: qt mouseevent qgraphicsitem qgraphicsscene


    【解决方案1】:

    项目的边界矩形在其局部坐标中定义项目,而在场景中设置其位置则使用场景坐标

    例如,让我们创建一个骨架Square 类,派生自QGraphicsItem

    class Square : public QGraphicsItem
    {
        Q_OBJECT
    public:
    
        Square(int size)
            : QGraphicsItem(NULL) // we could parent, but this may confuse at first
        {
            m_boundingRect = QRectF(0, 0, size, size);
        }
    
        QRectF boundingRect() const
        {
            return m_boundingRect;
        }
    
    private:
        QRectF m_boundingRect;
    };
    

    我们可以创建一个宽高为10的正方形

    Square* square = new Square(10);
    

    如果项目被添加到QGraphicsScene,它将出现在场景的左上角(0, 0);

    pScene->addItem(square); // assuming the Scene has been instantiated.
    

    现在我们可以在场景中移动square...

    square->setPos(100, 100);
    

    square 将移动,但其宽度和高度仍为 10 个单位。如果square的边界矩形改变了,那么矩形本身就改变了,但是它在场景中的位置还是一样的。让我们调整square的大小...

    void Square::resize(int size)
    {
        m_boundingRect = QRectF(0, 0, size, size);
    }
    
    square->resize(100);
    

    square 现在的宽度和高度都是 100,但它的位置是相同的,我们可以将 square 与其定义的边界矩形分开移动

    square->setPos(200, 200);
    

    我想要做的是将整个 QGraphicsItem 移动到一个设定的坐标。

    所以,希望这已经解释了边界矩形是项目的内部(局部坐标)表示,并且要移动项目,只需调用 setPos,它将相对于任何父项移动项目,或者如果没有parent 存在,它会相对于场景移动它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2013-10-13
      相关资源
      最近更新 更多