Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does QGraphicsItem::scenePos() keep returning (0,0)

I have been toying with this piece of code:

QGraphicsLineItem * anotherLine = this->addLine(50,50, 100, 100);
qDebug() << anotherLine->scenePos();

QGraphicsLineItem * anotherLine2 = this->addLine(80,10, 300, 300);
qDebug() << anotherLine2->scenePos();

Where the this pointer refers to a QGraphicsScene. In both cases, I get QPointF(0,0) for both output.
From reading the document, I thought scenePos() is supposed to return the position of the line within the scene, not where it is within its local coordinate system. What am I doing wrong?

like image 390
Extrakun Avatar asked Jul 20 '09 05:07

Extrakun


1 Answers

After reading the QT 4.5 documentation carefully on addLine, I realize what I have been doing wrong. According to the doc:

Note that the item's geometry is provided in item coordinates, and its position is initialized to (0, 0)

So if I specify addLine(50,50, 100, 100), I am actually modifying its local item coordinate. The assumption I made that it will be treated as a scene coordinate is wrong or unfounded. What I should be doing is this

// Create a line of length 100
QGraphicsItem * anotherLine = addLine(0,0, 100, 100); 

// move it to where I want it to be within the scene
anotherLine->setPos(50,50);

So if I am adding a line by drawing within the scene, I need to reset its centre to (0,0) then use setPos() to move it to where I want it to be in the scene.

Hope this helps anyone who stumble upon the same problem.

like image 91
Extrakun Avatar answered Sep 28 '22 21:09

Extrakun