2016-12-29 53 views
0

位置我有这样的构造方法,从QGraphicsRectItem派生的类:Qt的 - 我如何获得的QGraphicsItem的相对于现场

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功能,应在创建子弹矩形的中心:

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

加子弹的代码请 – eyllanesc

+0

@eyllanesc固定 – tomgrin10

回答

1

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

如果你想在中心现场的位置,你可以做这样的事情:

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