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

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

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

Tags:

C++

Qt

Qpainter