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