How can we know the width and height of string?

To manually get the size of a string, you need to use the QFontMetrics class. This can be manually used like this:

QFont font("times", 24);
QFontMetrics fm(font);
int pixelsWide = fm.width("What's the width of this text?");
int pixelsHigh = fm.height();

If you want to calculate it for the font used in a given widget (which you may not know), then instead of constructing the fontmetrics, get it from the widget:

QFontMetrics fm(button->fontMetrics());
int pixelsWide = fm.width("What's the width of this text?");
int pixelsHigh = fm.height();

Then you can resize the widget to exactly this value.

Tags:

Qt

Qt4