Search code examples
c++qtqgraphicsitem

Position of a QGraphicsItem in scene always NULL


For testing purposes, I am trying to draw several rectangles on a scene and add some text inside. The rectangles are supposed to be displayed in one column. They are, but the problem is that the text isn't. All the text is stacked on the top left of the scene.

Futhermore, pos() and scenePos() always return (0,0) for every box and text.

Here is the code responsible for that:

QHash<QString,Picto> Palette::getPics(){
    SpriteSheetManager ssm("sprite_zone"); 
    QList<QString> picNames = ssm.finder->allPic(); //Get all string to be displayed
    QHash<QString,Picto> picList;

    for(int i = 0; i < picNames.size(); i++){
        QString picName = picNames.at(i);
        QGraphicsTextItem *label = new QGraphicsTextItem();
        label->setPlainText(picName);
        QGraphicsRectItem *rect = new QGraphicsRectItem();
        rect->setRect(0,i*20,50,20);
        label->setParentItem(rect);
        label->setPos(0,0);
        this->addItem(rect);
        qDebug()<< rect->pos(); //always return (0,0)
    }
    return picList;
}

Can anybody tell me what I'm doing wrong?

I've tried this code with several variations, but I can't solve this.


Solution

  • Try this:

    for(int i = 0; i < 5; i++){
        QString picName = "Sample";
        QGraphicsTextItem *label = new QGraphicsTextItem();
        label->setPlainText(picName);
        QGraphicsRectItem *rect = new QGraphicsRectItem();
        rect->setRect(0,i*50,50,20);
        label->setParentItem(rect);
        label->moveBy(0,i*50);//new
        //or label->setPos(0,i*50);
        this->addItem(rect);
        qDebug()<< rect->pos();
    }
    

    Output of qDebug()<< rect->rect()<< label->scenePos();

    QRectF(0,0 50x20) QPointF(0, 0) 
    QRectF(0,50 50x20) QPointF(0, 50) 
    QRectF(0,100 50x20) QPointF(0, 100) 
    QRectF(0,150 50x20) QPointF(0, 150) 
    QRectF(0,200 50x20) QPointF(0, 200) 
    

    Result:

    enter image description here

    Edit:

    Calling setRect() on a QGraphicsRectItem does not change its pos(), it just changes the position of the rectangle that it draws, but the item's position is unchanged. So you can set rect as (0, 0) and call setPos() to move item where you want. So next code is slightly different but result on scene is absolutely same.

    for(int i = 0; i < 5; i++){
        QString picName = "Sample";
        QGraphicsRectItem *rect = new QGraphicsRectItem();
        QGraphicsTextItem *label = new QGraphicsTextItem();
        label->setPlainText(picName);
        rect->setRect(0,0,50,20);
        rect->setPos(0,i*50);
        //rect->moveBy(0,i*50);
        label->setParentItem(rect);
        //label->setPos(0,i*50);
        this->addItem(rect);
    }
    

    In this case pos() returns correct value