Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we know the width and height of string?

Tags:

qt

qt4

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

like image 590
user896036 Avatar asked Oct 24 '11 07:10

user896036


People also ask

How to find width of string in js?

The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels. The element is then removed using the removeChild() method. Method 2: Using the canvas measureText() method: A new “canvas” element is created with the createElement() method.

How to find width of text in HTML?

The measureText() method returns an object that contains the width of the specified text, in pixels. Tip: Use this method if you need to know the width of a text, before writing it on the canvas.

How do I measure text size?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.


1 Answers

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.

like image 127
duncan Avatar answered Oct 06 '22 00:10

duncan