How to get the sizes of the rendered text on a QPainter?
Asked Answered
J

2

21

I draw in my Qt program on a QPainter the text and various elements round it. I need to get the sizes in pixels which will be occupied by this text.

Can I get somehow the sizes in pixels, knowing a text string and a font?

Thanks.

Jermaine answered 2/6, 2013 at 1:56 Comment(0)
S
36

You can use QFontMetrics for the purpose. Following is sample from Qt Docs.

 QFont font("times", 24);
 QFontMetrics fm(font);
 int pixelsWide = fm.width("What's the width of this text?");
 int pixelsHigh = fm.height();
Slavey answered 2/6, 2013 at 2:37 Comment(1)
Note that QPainter's boundingRect() methods will also do this, with the painter's current font.Karney
C
4

The QPainter's boundingRect() will return a rectangle that you can use to get "width" and "height":

        QPainter qp(this);
        QFont font = qp.font();
        font.setPixelSize(24);
        qp.setFont(font);
        qp.setPen(Qt::white);
        QString text = "Hello, World!";
        QRect br = qp.boundingRect(0, 0, 150, 30, 0, text);
        qDebug() << br.width();
        qDebug() << br.height();
Cati answered 16/11, 2020 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.