Why does QGraphicsItem::scenePos() keep returning (0,0)
Asked Answered
L

1

10

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?

Lecher answered 20/7, 2009 at 5:34 Comment(0)
L
23

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.

Lecher answered 20/7, 2009 at 6:24 Comment(2)
I've spent one afternoon hunting this down! Thank you so much! (even if this thread is 3 years old)Blandish
Still very helpful after almost 15 years :) To understand a bit better why this works, I also found this post enlightening: forum.qt.io/post/403605Disheveled

© 2022 - 2024 — McMap. All rights reserved.