我有一个派生自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);
}
当函数运行时,它会在场景的开头创建一个项目符号。
我该怎么做才能解决这个问题?
我检查了其他问题,但他们的答案对我没有用。
答案 0 :(得分:1)
在QGraphicsRectItem
中,位置不在矩形的左上角,而是默认的项目位置(0,0)。
如果你想要中心的场景位置,你可以这样做:
QPointF Tower::sceneCenter()
{
return mapToScene(rect().center());
}