[英]Qt - How do I get a QGraphicsItem's position relative to scene
I have this constructor for a class that derives from QGraphicsRectItem
: 我有一个从
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: 我有一个用于
fire
功能的代码,该代码应在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::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). 在
QGraphicsRectItem
该位置不在矩形的左上角,而是默认项的位置(0,0)。
If you want the scene position of the center you can do something like this: 如果您想要中心的场景位置,则可以执行以下操作:
QPointF Tower::sceneCenter()
{
return mapToScene(rect().center());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.