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

时间:2016-12-29 00:48:53

标签: c++ qt

我有一个派生自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函数的代码,它应该在Rectangle的中心创建一个项目符号:

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

当函数运行时,它会在场景的开头创建一个项目符号。
我该怎么做才能解决这个问题?

我检查了其他问题,但他们的答案对我没有用。

1 个答案:

答案 0 :(得分:1)

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

如果你想要中心的场景位置,你可以这样做:

QPointF Tower::sceneCenter()
{
    return mapToScene(rect().center());
}
相关问题