How can we know the width and height of string?

2019-06-15 13:56发布

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

标签: qt qt4
2条回答
再贱就再见
3楼-- · 2019-06-15 14:16

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.

查看更多
登录 后发表回答