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

橙三吉。 提交于 2019-11-30 15:19:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1151849/why-does-qgraphicsitemscenepos-keep-returning-0-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!