Pregunta

I have this simple piece of code in a class constructor which is inherited from QGraphicsScene :

setSceneRect(0,0,800,800);
addRect(sceneRect());
QGraphicsRectItem*r1 = addRect(200, 0, 5, 5);
qDebug()<<r1->pos();

Here I add a rect at pos(200,0) but qDebug() prints QPointF(0, 0)! I'm totally confused. Even scenePos returns (0,0)! Is it true?!

¿Fue útil?

Solución

The rect is at position (200, 0) inside the item's coordinate system, but the item itself is at (0,0) in its parent's coordinate system.

The QGraphicsScene::addRect() documentation explains this:

Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0). For example, if a QRect(50, 50, 100, 100) is added, its top-left corner will be at (50, 50) relative to the origin in the items coordinate system.

Alternatively, you can add a rectangle at 0, 0, 5, 5) and move the item afterwards, to get the result you expected:

QGraphicsRectItem* r1 = addRect(0, 0, 5, 5);
r1->setPos(200, 0);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top