2014-10-20 30 views
1

出於測試目的,我試圖在場景上繪製幾個矩形並在其中添加一些文本。矩形應該顯示在一列中。他們是,但問題是文本不是。所有文本都堆疊在場景的左上角。QGraphicsItem在場景中的位置始終爲空

而且,pos()scenePos()總是爲每個文本框和文本返回(0,0)。

下面是代碼負責人認爲:

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; 
} 

誰能告訴我什麼,我做錯了什麼?

我試過這個代碼有幾個變化,但我不能解決這個問題。

回答

2

試試這個:

輸出的 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) 

結果

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(); 
} 

enter image description here

編輯:

QGraphicsRectItem上調用setRect()不會更改它的pos(),它只會更改它繪製的矩形的位置,但該項目的位置不變。所以你可以將rect設置爲(0, 0)並且調用setPos()將物品移動到你想要的位置。所以下一個代碼略有不同,但在場景中的結果是完全相同的。

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); 
} 

在這種情況下pos()返回正確的值

+0

這意味着你必須移動標籤本身,不是嗎?我強硬它應該與它的父母一起移動,因爲它的位置應該是相對於父母的。 – Laetan 2014-10-20 11:50:04

+0

@Laetan是的,我移動標籤。是的,它相對於父母,但正如你所說,你的父母每次都有0,0個座標,所以標籤的座標也是0,0。 – Chernobyl 2014-10-20 12:04:38

+0

我知道,但這就是問題所在。爲什麼直角座標顯然不位於視圖上的0,0位置時總會有(0,0),並且我如何設置它以便正確的位置用於兒童物品? – Laetan 2014-10-20 12:24:55