Re: Determining the width of a GtkTextView in characters

Eduardo M KALINOWSKI wrote:


   I have a GtkTextView whose contents is all in one font, a monospaced
font by the way. I want to know the width of the GtkTextView in
characters, that is, how many characters fit in a line. I've tried a
code like this:

OK, I've found a code that does exactly what I want in another program.
Here it is, as a reference for those that need to do the same in the future:

  GdkRectangle          rect;
  PangoContext         *context;
  PangoGlyphString     *glyphs;
  GList                *items;
  PangoItem            *item;
  PangoAttrList        *attrib;
  int                   char_width;

  /* Get the size of the window */
  gtk_text_view_get_visible_rect(txtView, &rect);

  /* Get the Pango context */
  context = gtk_widget_get_pango_context(GTK_WIDGET(txtView));

  /* Determine the width of the W character. Any should do, supposing
     the font is monospaced. If not, W is a wide character. */
  attrib = pango_attr_list_new();
  glyphs = pango_glyph_string_new();
  items  = pango_itemize(context, "W", 0, 1, attrib, NULL);
  item   = (PangoItem *) items->data;
  pango_shape("W", 1, &item->analysis, glyphs);
  char_width  = PANGO_PIXELS(glyphs->glyphs[0].geometry.width);

  cols  = rect.width / char_width;

Naturally, it will only work correctly for monospaced fonts (which is
what I am using). But for variable width fonts, it should return a
conservative value, as W is generally one of the widest characters.

Household hint:
        If you are out of cream for your coffee, mayonnaise makes a
        dandy substitute.

ekalin bol com br

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]