I want to create a button exactly the same size as the string for this i want the width and height of the string.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With