Qt - 如何获取 QGraphicsItem 相对于场景的位置

Qt - How do I get a QGraphicsItem's position relative to scene

本文关键字:相对于 QGraphicsItem 位置 获取 何获取 Qt      更新时间:2023-10-16

我有一个从 QGraphicsRectItem派生的类的构造函数:

Tower::Tower(int x, int y, QGraphicsScene *scene) : QGraphicsRectItem(x, y, width, height)
{
    QBrush brush;   // color it
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(START_COLOR);
    this->setBrush(brush);
    this->setAcceptHoverEvents(true);
    scene->addItem(this);   // add to scene
}

我有一个fire函数的代码,该函数应在矩形的中心创建子弹:

void Tower::fire()
{
    Bullet *bullet = new Bullet(scenePos().x() + width / 2, scenePos().y() + height / 2, scene());
}

这是Bullet的代码:

Bullet::Bullet(int x, int y, QGraphicsScene *scene) : QGraphicsRectItem(x, y, width, height)
{
    QBrush brush;   // color it
    brush.setStyle(Qt::SolidPattern);
    brush.setColor(color);
    this->setBrush(brush);
    scene->addItem(this);
}

当功能运行时,它会在场景开头创建子弹。
我该怎么办来解决这个问题?

我检查了其他问题,但他们的答案对我不起作用。

QGraphicsRectItem中,位置不在矩形的左上角,而是默认项目位置(0,0)。

如果您想要中心的场景位置,则可以做类似的事情:

QPointF Tower::sceneCenter()
{
    return mapToScene(rect().center());
}