qt - 如何更改 QGraphicsScene 上 QGraphicsItem 的 borderingRect() 的位置?

标签 qt mouseevent qgraphicsitem qgraphicsscene

我已将 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);
}

最佳答案

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

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

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.

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

square->setPos(100, 100);

正方形将会移动,但其宽度和高度仍为 10 个单位。如果正方形的边界矩形发生变化,则矩形本身也会发生变化,但其在场景中的位置仍然相同。让我们调整正方形的大小...

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

square->resize(100);

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

square->setPos(200, 200);

What I want to be able to do is move the entire QGraphicsItem to a set coordinate.

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

关于qt - 如何更改 QGraphicsScene 上 QGraphicsItem 的 borderingRect() 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610682/

相关文章:

jQuery 可拖动 : the draggable box go over the container - bug?

c++ - Qt:在另一个 QGraphicsItem C++ 中限制 QGraphicsItem 的可移动区域

c++ - 调整 QGraphicsItem 的大小不会更新 Item 属性

c++ - 使用 Qt 在 C++ 中将事件从 QGraphicsScene 传递到 QGraphicsItem

c++ - 如何从 QSS 选择 QTextBrowser 中的 href 标签?

javascript - 将 onclick 事件添加到循环内的各个 div

c++ - QT CQTDeployer无法运行: config/controlScript.js (SOLVED)

每次我停止点击时,Java 点击计数器都会重置

c++ - qt creator 如何从主窗口获取布局?

c++ - 通过 vector 中对象的各个方面处理崩溃循环