Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top