Reputation: 741
I'm trying to vertically center the text of a label inside a box. This is do code I'm trying:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
win = Gtk.Window()
win.set_default_size(200, 100)
box = Gtk.Box()
win.add(box)
lbl = Gtk.Label("FOO")
lbl.set_vexpand(True)
lbl.set_valign(Gtk.Align.CENTER)
# Set the background to make the problem visible
lbl.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(red=1, green=0, blue=0))
box.add(lbl)
win.show_all()
win.connect('destroy', Gtk.main_quit)
Gtk.main()
As you can see, the label itself is centered perfectly fine inside the box, but the text inside the label is shifted slightly towards the top end of the label:
I'm not able to find anything about this. Programmatic as well as CSS-based solutions are highly appreciated.
Upvotes: 1
Views: 1876
Reputation: 1091
I believe the problem is that you and the font creator have different opinions of what "centered" in the vertical sense means. Also think what will happen to the visual impression if you have characters like y and g. This will get even more confusing if you add international characters to the mix like Å or Ö.
Anyway, this answer uses CSS to create a configurable offset (padding-top), and will also give you freedom to change font. The 20 px value is obviously too much, but will give a clear visible evidence that it works.
style.css
:
#custom_label {
padding-top: 20px;
background-color: red;
font: Vera 20px;
}
test.py
:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
win = Gtk.Window()
win.set_default_size(200, 100)
box = Gtk.Box()
win.add(box)
lbl = Gtk.Label(u'FOO')
lbl.set_name('custom_label')
box.add(lbl)
style_provider = Gtk.CssProvider()
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
with open("style.css") as f:
style_provider.load_from_data(f.read())
win.show_all()
win.connect('destroy', Gtk.main_quit)
Gtk.main()
As a bonus, if you start your program with:
GTK_DEBUG=interactive python test.py
(assuming Linux, not sure how to do this in Windows), you will have an interactive way to change the CSS and other widget properties.
Upvotes: 1