Search code examples
c++qttextqgraphicsitem

Qt Scaling Custom QGraphicsItem with unscaled text


I'm trying to create customObject (rectangle and it inherit from QGraphicsItem) that will be painted on scene with ceratin text(stored in attribute), but when I scale it - i wish to keep same size of text. Here is my over. paint function:

    void CustomRectangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *options, QWidget *widget)
    {
        QColor currentColor = get_ColorByCurrentState();

        QRectF rect = boundingRect();
        QPen pen(currentColor, Own_LineWidith);

        painter->setPen(pen);
        painter->drawRect(rect);

        QRectF rect_text(rect.x(), rect.y(),100,100);
        painter->drawText(rect_text,this->getText() );
    }

and my two scaling functions:

    void CustomObject::scaleUp()
    {
        scale(ScaleFactor_X,ScaleFactor_Y);
    }

    void CustomObject::scaleDown()
    {
        scale(1/ScaleFactor_X,1/ScaleFactor_Y);
    }

But text still keep scaling along with rectangle.

EDIT 1 I tried adding it another way, i nfucntion that creates and adds my rectangle to scene (here - named "newObject"), but result is still the same.

    QGraphicsTextItem* GTI = new QGraphicsTextItem(newObject->toStringForScene(), newObject);

I'm beginign to think that I shoud create each text object as separeted object and save it different list. Ofcours, i would have to update it then, whenever it's object moved.


Solution

  • I resolved this with QGraphicsTextItem's poitner as class's attribute.

    QGraphicsTextItem* GTI;
    

    I initialzie it in constructor:

    GTI_Description = new  QGraphicsTextItem(this->toStringForScene());
    

    and then I call function to updated it's X and Y:

    void updateTextPosition()
    {
        GTI->setX( this->x() );
        GTI->setY( this->y() );
    }
    

    and to add it to the scene:

    addTextToScene(DragScene* _scene)
    {
        updateDescriptionPosition();
        _scene->addItem(GTI_GTI);
        _scene->update();
    }
    

    Then i just call updateTextPosition() whenerver I change positions (in my mouseRelease event's handler).