I have this constructor for a class that derives from 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
}
And I have this code for a fire
function which should create a bullet at the center of the Rectangle:
void Tower::fire()
{
Bullet *bullet = new Bullet(scenePos().x() + width / 2, scenePos().y() + height / 2, scene());
}
This is the code for 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);
}
When the function runs it creates a bullet at the beginning of the scene.
What can I do to fix this?
I checked other questions but their answers didn't work for me.
In QGraphicsRectItem
the position is not at the top left corner of the rectangle, but is the default item position (0, 0).
If you want the scene position of the center you can do something like this:
QPointF Tower::sceneCenter()
{
return mapToScene(rect().center());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.