diff options
author | Matthias Clasen <mclasen@redhat.com> | 2021-07-02 21:20:39 -0400 |
---|---|---|
committer | Matthias Clasen <mclasen@redhat.com> | 2021-07-02 21:31:32 -0400 |
commit | ed5b42071c26829024c0c4d4459e34548fb68957 (patch) | |
tree | e1b834f3e207368479895796bedff661989352d6 /examples | |
parent | a90f721b744b4853c4afed742b4a8e1842a63468 (diff) | |
download | gtk+-ed5b42071c26829024c0c4d4459e34548fb68957.tar.gz |
Add a simple python example
This shows how to do custom drawing in a widget,
implemented in python. The example sets up the
environment for running from the toplevel dir,
assuming that the build dir is called 'build'.
Diffstat (limited to 'examples')
-rwxr-xr-x | examples/squares.py | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/examples/squares.py b/examples/squares.py new file mode 100755 index 0000000000..5aea3d32cd --- /dev/null +++ b/examples/squares.py @@ -0,0 +1,61 @@ +#!/usr/bin/env -S GI_TYPELIB_PATH=${PWD}/build/gtk:${GI_TYPELIB_PATH} LD_PRELOAD=${PWD}/build/gtk/libgtk-4.so python3 + +import gi + +gi.require_version('Gdk', '4.0') +gi.require_version('Gtk', '4.0') + +from gi.repository import Gdk +from gi.repository import Gtk +from gi.repository import Graphene + + +class DemoWidget(Gtk.Widget): + + __gtype_name__ = "DemoWidget" + + def __init__(self): + super().__init__() + + def do_measure(self, orientation, for_size: int): + # We need some space to draw + return 100, 200, -1, -1 + + def do_snapshot(self, snapshot): + # Draw four color squares + color = Gdk.RGBA() + rect = Graphene.Rect.alloc() + + width = self.get_width() / 2 + height = self.get_height() / 2 + + Gdk.RGBA.parse(color, "red") + rect.init(0, 0, width, height) + snapshot.append_color(color, rect) + + Gdk.RGBA.parse(color, "green") + rect.init(width, 0, width, height) + snapshot.append_color(color, rect) + + Gdk.RGBA.parse(color, "yellow") + rect.init(0, height, width, height) + snapshot.append_color(color, rect) + + Gdk.RGBA.parse(color, "blue") + rect.init(width, height, width, height) + snapshot.append_color(color, rect) + +def on_activate(app): + # Create a new window + win = Gtk.ApplicationWindow(application=app) + win.set_title("Squares") + icon = DemoWidget() + win.set_child(icon) + win.present() + +# Create a new application +app = Gtk.Application(application_id='org.gtk.exampleapp') +app.connect('activate', on_activate) + +# Run the application +app.run(None) |