How can we know the width and height of string?

醉酒当歌 提交于 2019-12-08 15:09:44

问题


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



来源:https://stackoverflow.com/questions/7872462/how-can-we-know-the-width-and-height-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!