PDA

View Full Version : co-ordinate confusion: scenePos()



Urthas
14th March 2010, 19:53
Hello!

I'm learning Qt's graphics framework by way of playing with a simple application that draws some rectangles on a scene. I understand that item co-ordinates are given in terms of the item's local co-ordinates, such that for a given item, the position is (0, 0). What I don't understand is why calling scenePos() on all the items returns (0, 0) for each one. Qt isn't lying, but how can the scenePos() for items that appear in the expected different locations be the same, and specifically why are they all 0? Here is the code:



MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
scene = new QGraphicsScene();
scene->setSceneRect(0, 0, 1024, 768);
QGraphicsRectItem *rect1 = scene->addRect(scene->width() / 4, scene->height() / 4, 10, 10);
QGraphicsRectItem *rect2 = scene->addRect(scene->width() / 3, scene->height() / 3, 20, 20);
QGraphicsRectItem *rect3 = scene->addRect(scene->width() / 2, scene->height() / 2, 30, 30);

qDebug() << rect1->pos() << ", " << rect2->pos() << ", " << rect3->pos(); // 3x QPointF(0, 0) -- fine
qDebug() << rect1->scenePos() << ", " << rect2->scenePos() << ", " << rect3->scenePos(); // 3x QPointF(0, 0) -- what?

view = new QGraphicsView(scene, this);
this->setCentralWidget(view);
}


Thanks in advance for any insights.

Urthas
14th March 2010, 20:05
Hmm well after posting this I saw similar threads where the intuitively appropriate position values are returned if after instantiating the items, setPos() is called. Perhaps the documentation for addRect() etc. should include QGraphicsItem::setPos() in it's "see also".

norobro
15th March 2010, 02:14
Try using boundingRect() -
qDebug() << rect1->boundingRect().topLeft()

Urthas
15th March 2010, 03:12
Try using boundingRect() -
qDebug() << rect1->boundingRect().topLeft()

Yes, that worked, thank you so much. I was able to instantiate my rectangles and then get meaningful co-ordinate values back from boundingRect() as opposed to rect(), without having to setPos() beforehand. But it is confusing as hell. Why does boundingRect() Do What I Mean but rect() doesn't? Why doesn't an item adopt as its rect(), pos() and scenePos() values the co-ordinates that it is instantiated with (ie., scene->addRect(x, y, side, side)? Why do these things seem so...unintuitive?