[Qt-interest] QGraphicsTextItem adjustSize()

Sean Harmer sean.harmer at maps-technology.com
Mon Feb 23 18:32:00 CET 2009


On Monday 23 February 2009 17:03:45 Stacy Alley wrote:
> Hello,
> I'm working with a very large QGraphicsScene (width =1.92991e+08
> height=9.86328e+07)
> I add QGraphicsPolygonItems to the scene that represent a footprint of
> image data.  I'm also trying to add
> a QGraphicsTextItem on top of the polygon item to label the footprint
> with it's filename.  I'm having a hard time
> setting the size for the font of the text item.  I just found the
> QGraphicsItem::adjustSize() method, but that did not
> do anything.  Well, at least I can't see what it did because I can not
> even see the text item.  (Font too small I believe.)
> Does anybody have an hints for me as to how I set the font size for
> these text items?
You're in luck I was fighting with this at the weekend! Implement the 
resizeEvent() function for the item that contains your QGraphicsTextItem and 
do something like this:

void Plot::resizeEvent( QGraphicsSceneResizeEvent* )
{
    // Centre the contained text item
    QTransform m = sceneTransform();
    m_text->resetTransform();
    m_text->scale( 1.0 / m.m11(), 1.0 / m.m22() );
    QRectF m_textRect = m_text->boundingRect();
    QPolygonF itemTextPoly = m_text->mapToItem( this, m_textRect );
    QRectF itemTextRect = itemTextPoly.boundingRect();
    double dx = 0.5 * m.m11() * ( rect().width() - itemTextRect.width() );
    double dy = 0.5 * m.m22() * ( rect().height() - itemTextRect.height() );
    m_text->translate( dx, dy );
}

The basic idea is to scale by the inverse of the transform applied by the 
scene. That way you can set a sensible font size and it should be scaled to 
your scene as you expect.

HTH,

Sean



More information about the Qt-interest-old mailing list