How can we know the width and height of string?

2019-06-15 13:48发布

问题:

I want to create a button exactly the same size as the string for this i want the width and height of the string.

回答1:

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.



回答2:

Use QFontMetrics.

Example: http://www.developer.nokia.com/Community/Wiki/CS001349_-_Calculating_text_width_in_Qt



标签: qt qt4