![](/img/trans.png)
[英]How can I know if a QGraphicsItem created in a separate class has moved on a scene (changed it's position)?
[英]Qt - How do I get a QGraphicsItem's position relative to scene
我有一个从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);
}
该函数运行时,它将在场景开始时创建一个项目符号。
我该怎么做才能解决此问题?
我检查了其他问题,但他们的答案对我不起作用。
在QGraphicsRectItem
该位置不在矩形的左上角,而是默认项的位置(0,0)。
如果您想要中心的场景位置,则可以执行以下操作:
QPointF Tower::sceneCenter()
{
return mapToScene(rect().center());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.