[pygobject] gtk overrides: Make GTK4 widgets iterable



commit 0453702ff4e3001aae89594243b746258782b2d5
Author: Jean Felder <jfelder src gnome org>
Date:   Sat Nov 21 17:43:25 2020 +0100

    gtk overrides: Make GTK4 widgets iterable
    
    GTK4 removed the Gtk.Container interface, and added API on Gtk.Widget
    to iterate over children instead.
    
    Making Widgets iterable allows to easily loop over the children and
    check is a widget is a child of an other one.
    
    A new test is also added.

 gi/overrides/Gtk.py         | 10 ++++++++++
 tests/test_overrides_gtk.py | 31 +++++++++++++++++++++++++++++++
 2 files changed, 41 insertions(+)
---
diff --git a/gi/overrides/Gtk.py b/gi/overrides/Gtk.py
index 5b810b60..721e5317 100644
--- a/gi/overrides/Gtk.py
+++ b/gi/overrides/Gtk.py
@@ -135,6 +135,16 @@ class Widget(Gtk.Widget):
 
     translate_coordinates = strip_boolean_result(Gtk.Widget.translate_coordinates)
 
+    if GTK4:
+        def __contains__(self, child):
+            return child in list(self)
+
+        def __iter__(self):
+            child = self.get_first_child()
+            while child:
+                yield child
+                child = child.get_next_sibling()
+
     if GTK2 or GTK3:
         def freeze_child_notify(self):
             super(Widget, self).freeze_child_notify()
diff --git a/tests/test_overrides_gtk.py b/tests/test_overrides_gtk.py
index 61cff2cb..6337d7c4 100644
--- a/tests/test_overrides_gtk.py
+++ b/tests/test_overrides_gtk.py
@@ -902,6 +902,37 @@ class TestGtk(unittest.TestCase):
         pixbuf = button.render_icon(Gtk.STOCK_OK, Gtk.IconSize.BUTTON)
         self.assertTrue(pixbuf is not None)
 
+    @unittest.skipUnless(
+        Gtk_version == "4.0", "GtkWidget prior to gtk4 is not iterable")
+    def test_widget_iterable(self):
+        widget = Gtk.Box()
+
+        children = [child for child in widget]
+        self.assertEqual(len(children), 0)
+
+        nr_children = 7
+        for i in range(nr_children):
+            widget.append(Gtk.Label())
+
+        children = [child for child in widget]
+        self.assertEqual(len(children), nr_children)
+
+        first_child = children[0]
+        last_child = children[-1]
+        self.assertEqual(first_child, widget.get_first_child())
+        self.assertEqual(last_child, widget.get_last_child())
+
+        self.assertTrue(first_child in widget)
+        self.assertTrue(last_child in widget)
+
+        widget.remove(first_child)
+        self.assertTrue(first_child not in widget)
+        self.assertTrue(last_child in widget)
+
+        widget.remove(last_child)
+        self.assertTrue(first_child not in widget)
+        self.assertTrue(last_child not in widget)
+
 
 @unittest.skipUnless(Gtk, 'Gtk not available')
 class TestWidget(unittest.TestCase):


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