qtfont-sizezoomingqgraphicstextitem

Preventing font scale in QGraphicsItem


I am using QGraphicsTextItem to paint the text on the scene. Text is painted along the path (QGraphicsPathItem), wich is parent of my QGraphicsTextItem - so the text rotation is changed to be along the path element and is sticked to it while zooming the view. But the font size of QGraphicsTextItem is also changing while zooming the view - this is what I am trying to avoid. Of I set QGraphicsItem::ItemIgnoresTransformations flag to the QGraphicsTextItem it stops rotating while it's parent (QGraphicsPathItem) does.

enter image description here

I do understand that I have to re-implement QGraphicsTextItem::paint function, but I am stuck with the coordination system. Here is the code (Label class inherits public QGraphicsTextItem):

void Label::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
    // Store current position and rotation
    QPointF position = pos();
    qreal angle = rotation();

    // Store current transformation matrix
    QTransform transform = painter->worldTransform();

    // Reset painter transformation
    painter->setTransform( QTransform() );

    // Rotate painter to the stored angle
    painter->rotate( angle );

    // Draw the text
    painter->drawText( mapToScene( position ), toPlainText() );

    // Restore transformation matrix
    painter->setTransform( transform );
}

The position (and rotation) of my text on the screen is unpredictable :( What am I doing wrong? Thank you very much in advance.


Solution

  • The following solution worked perfectly for me:

    void MyDerivedQGraphicsItem::paint(QPainter *painter, const StyleOptionGraphicsItem *option, QWidget *widget)
    {
        double scaleValue = scale()/painter->transform().m11();
        painter->save();
        painter->scale(scaleValue, scaleValue);
        painter->drawText(...);
        painter->restore();
        ...
    }
    

    We can also multiply the scaleValue by other mesures we want to keep its size constant outside the save/restore environment.

    QPointF ref(500, 500);
    QPointF vector = scaleValue * QPointF(100, 100);
    painter->drawLine(ref+vector, ref-vector);