首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更改QGraphicsItem的QGraphicsItem()在QGraphicsScene上的位置?

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

Stack Overflow用户
提问于 2016-01-05 11:31:24
回答 1查看 4.6K关注 0票数 2

我已经在现场将我的boundingRect() QGraphicsItem设置为一个特定的坐标。如何根据QGraphicsItem::mouseMoveEvent更改坐标

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

代码语言:javascript
复制
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()
    }

}

场景为880x860年,boundingRect()设置如下:

代码语言:javascript
复制
QRectF QGraphicsItem::boundingRect() const
{
    return QRectF(780,425,60,30);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-05 12:02:55

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

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

代码语言:javascript
复制
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的正方形。

代码语言:javascript
复制
Square* square = new Square(10);

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

代码语言:javascript
复制
pScene->addItem(square); // assuming the Scene has been instantiated.

现在我们可以在现场移动square了.

代码语言:javascript
复制
square->setPos(100, 100);

square会移动,但它的宽度和高度仍然是10个单位。如果square的边框发生变化,那么rect本身就会发生变化,但是它在场景中的位置仍然是一样的。让我们调整square的尺寸..。

代码语言:javascript
复制
void Square::resize(int size)
{
    m_boundingRect = QRectF(0, 0, size, size);
}

square->resize(100);

square现在的宽度和高度为100,但是它的位置是相同的,我们可以从它定义的边框中分别移动square

代码语言:javascript
复制
square->setPos(200, 200);

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

因此,希望这已经解释了,边框是项目的内部(局部坐标)表示,要移动项目,只需调用setPos,它将相对于任何父项移动项目,或者如果没有父项,它将相对于场景移动它。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34610682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档