| FAQ Index - Search - Recent Changes - Everything - Add entry |
4.15. Can I find out how long (wide) a string is in a certain font?
In PyGTK2, you can use pango calls to find out how wide a string will be, using the pango context of the widget that contains (or that will contain) your text:
context = widget.get_pango_context()
metrics = context.get_metrics('font name, 12')
width = pango.PIXELS(metrics.get_approximate_char_width() * n_chars)
(See FAQ 4.14 to understand how PIXELS() works)
For a monospaced font, this should be quite accurate. You can then use widget.set_size_request() if you would like to set that width as the minimum width for the widget/view.
In PyGTK-0.6, you can ask the font directly how long a given string is going to be, as well as how high. Retrieve the font object from the style, and then query it with the string in question:
font = widget.get_style().font h = font.height(my_string) w = font.width(my_string)The methods return pixel counts. You can then set the size manually to any function of those parameters. For instance, to make a widget twice as wide and as high as the string you measured with, use:
widget.set_usize(w*2, h*2)[Credit: Andrew Reid <Andrew-dot-Reid-at-nist-dot-gov>]
