Exhuming this old thread with apparently no final answer.

I found that one of the issue in the initial code was the call to
“modify_font”.

I replaced it with a call to “set_font_description” on the layout.

 

This is the working code, that takes markup into account:

 

def get_pango_string_size(str, font_name=TEXT_FONT):

    label           = gtk.Label()

    pango_layout    = label.get_layout()

    pango_layout.set_markup(str)

    pango_font_desc = pango.FontDescription(font_name)

    pango_layout.set_font_description(pango_font_desc)

    return pango_layout.get_pixel_size()

 

Hope this helps.

Thanks

 

-David

 

 <http://www.daa.com.au/mailman/listinfo/pygtk> vladovi at atlas.cz wrote:
> Walter Leibbrandt < <http://www.daa.com.au/mailman/listinfo/pygtk> walter
at translate.org.za> napsal(a) :
> 
>   
>> Hi,
>> 
>> Vladimír Jícha wrote:
>>     
>>> Hello,
>>> 
>>> I'm trying to get width of a text string. I found a FAQ 4.15 
>>> ( <http://faq.pygtk.org/index.py?req=show&file=faq04.015.htp>
http://faq.pygtk.org/index.py?req=show&file=faq04.015.htp) which has a 
>>> solution for this. But unfortunately it doesn't work. If I use "font = 
>>> widget.get_style().font", I get following error message: AttributeError:

>>> 'gtk.Style' has no attribute 'font'.
>>> 
>>> Is the FAQ outdated? What syntax should I use?
>>> 
>>> Thank yo
>>>       
>> Try widget.get_style().get_font().
>> 
>>     
> 
> Thanks for your answer. Unfortunately it doens't work correctly for me. I
have following 2 problems:
> 1) I get a DeprecationWarning for the line.
> 2) No matter what fond and size I use, I get the same width.
> 
> Sample code:
> 
>         label = gtk.Label()
>         name_font = pango.FontDescription("Times 10")
>         label.modify_font(name_font)
>         font = label.get_style().get_font()
>         label2 = gtk.Label()
>         name_font2 = pango.FontDescription("Sans Bold 12")
>         label2.modify_font(name_font2)
>         font2 = label2.get_style().get_font()
>         print font.width("string"), font2.width("string")
> 
> I always get the same numbers. Is something wrong in my code?
>   
You should use the PangoLayout to retrieve the pixel size of the text. Use:
 
label.get_layout().get_pixel_size()
 
to get the width and height of the label string in pixels.
 
John

 

_______________________________________________
pygtk mailing list   pygtk@daa.com.au
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://faq.pygtk.org/

Reply via email to