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

后端 未结 1 1662
余生分开走
余生分开走 2021-01-02 10:43

I have been toying with this piece of code:

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


        
1条回答
  •  孤街浪徒
    2021-01-02 10:53

    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.

    0 讨论(0)
提交回复
热议问题