I have the following PyGObject code:
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GLib
class FontSizeApp(Gtk.Application):
def __init__(self):
super().__init__(application_id="com.example.FontSizeApp")
def do_activate(self):
window = Gtk.ApplicationWindow(application=app)
window.set_title("Font Size Experiment")
window.set_default_size(400, 100)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, margin_top=20, margin_bottom=20, margin_start=20, margin_end=20)
window.set_child(vbox)
button = Gtk.Button(label="Enlarge Text")
vbox.append(button)
self.entry = Gtk.Entry()
self.entry.set_name("entry1")
vbox.append(self.entry)
# Connect button signal
button.connect("clicked", self.on_button_clicked)
window.present()
def on_button_clicked(self, button):
css = """
#entry1 {
font-size: 30pt;
}
"""
style_provider = Gtk.CssProvider()
style_provider.load_from_data(css.encode())
Gtk.StyleContext.add_provider_for_display(
Gdk.Display.get_default(),
style_provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
# Tried the following but does not work
# self.entry.queue_resize()
# GLib.idle_add below works intermittently
GLib.idle_add(self._print)
def _print(self):
min_size, nat_size = self.entry.get_preferred_size()
print(f"Preferred height: {nat_size.height}")
if __name__ == "__main__":
from gi.repository import Gdk
app = FontSizeApp()
app.run()
where I use GTK4 to add an Entry widget, and then later, when a button is pressed, change its text size.
In the code I’m working on, we have a custom LayoutManager, so we must know the preferred size of the widget immediately (or a short while, but we need to know when) after I apply the Gtk Style provider. I then need to know the preferred height of the widget or when it’s ready and updated – I’ve tried using GLib.idle_add, that does work sometimes, but sometimes it does not (it prints 34 when it’s supposed to be 45). I’ve also tried to queue a resize, as shown in the code – so after applying CSS to a Entry widget, when can I know its new updated preferred height?
Thanks!