如何在QGraphicsScene上更改QGraphicsItem的boundingRect()的位置?

时间:2016-01-05 11:31:24

标签: qt mouseevent qgraphicsitem qgraphicsscene

我已将boundingRect()的{​​{1}}设置为场景中的某个坐标。如何根据QGraphicsItem

更改坐标

以下是我编写的代码。但是此代码仅将我在QGraphicsItem::mouseMoveEvent内绘制的形状的位置设置为boundingRect()内的坐标。我希望能够做的是将整个boundingRect()移动到设定坐标。

QGraphicsItem

场景是880乘860,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() } } 设置如下:

boundingRect()

1 个答案:

答案 0 :(得分:2)

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

例如,让我们创建一个从[{1}}

派生的骨架Square
QGraphicsItem

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

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;
};

如果该项目已添加到Square* square = new Square(10); ,它将显示在场景的左上角(0,0);

QGraphicsScene

现在我们可以移动场景中的pScene->addItem(square); // assuming the Scene has been instantiated. ...

square

square->setPos(100, 100); 会移动,但其宽度和高度仍为10个单位。如果更改了square的边界矩形,则rect本身会发生变化,但它在场景中的位置仍然相同。让我们调整square ...

的大小
square

void Square::resize(int size) { m_boundingRect = QRectF(0, 0, size, size); } square->resize(100); 现在的宽度和高度为100,但它的位置相同,我们可以将square与其定义的边界矩形分开移动

square
  

我希望能够将整个QGraphicsItem移动到设定的坐标。

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

相关问题