halexh
halexh

Reputation: 3121

Resize Window to X Characters (not pixels)

gtk_window_set_default_size() resizes the window based off of pixels. How would I do this if I wanted to resize it based on x amount of characters, and possibly taking into account the font size?

From what I have gathered searching on the internet, gtk_window_set_geometry_hints() seems to be based off of pixels too.

Upvotes: 2

Views: 151

Answers (1)

user4815162342
user4815162342

Reputation: 154886

You can always convert characters to pixels by obtaining the approximate char width from the font.

Starting with a relevant widget (such as a text view or whatever it is that holds the characters you actually care about), call gtk_widget_get_pango_context, then pango_context_load_font to get the font, pango_font_get_metrics to get the font metrics, and finally pango_font_metrics_get_approximate_char_width divided by PANGO_SCALE to get the char width. Demonstrated in PyGTK:

import gtk, pango

char_count = 80     # how many characters you have

w = gtk.Window()    # here you'd use another widget
ctx = w.get_pango_context()
metrics = ctx.load_font(ctx.get_font_description()).get_metrics()
char_width_pango = metrics.get_approximate_char_width()
pixel_count = char_count * char_width_pango / pango.SCALE
print pixel_count

Upvotes: 4

Related Questions