nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: MyreMylar/pygame_gui
Pull request #512 (2024-02-15 03:57:50)

Add set_container to elements
related to #507 


Patch:
diff --git a/pygame_gui/core/ui_element.py b/pygame_gui/core/ui_element.py
index 360a805..367883c 100644
--- a/pygame_gui/core/ui_element.py
+++ b/pygame_gui/core/ui_element.py
@@ -254,6 +254,21 @@ class UIElement(GUISprite, IUIElementInterface):
 
         if self.ui_container is not None and not self.ui_container.visible:
             self.visible = 0
+            
+    def set_container(self, container: Union[None, IContainerLikeInterface]):
+        """
+        Switch the element to new container.
+        Remove the element from the old container and add it to the new container.
+
+        :param container: The new container to add.
+
+        """
+        if isinstance(self.ui_container, IContainerLikeInterface):
+            self.ui_container.remove_element(self)
+            
+        self._setup_container(container)
+        self._update_absolute_rect_position_from_anchors()
+        self.rebuild_from_changed_theme_data()
 
     def _setup_container(self, container):
         if container is None:


Test patch:
diff --git a/tests/test_core/test_ui_element.py b/tests/test_core/test_ui_element.py
index 978fd87..a70122b 100644
--- a/tests/test_core/test_ui_element.py
+++ b/tests/test_core/test_ui_element.py
@@ -127,6 +127,18 @@ class TestUIElement:
         assert element_5.rect.topleft == (110, 110)
         element_5.update_containing_rect_position()
         assert element_5.rect.topleft == (60, 60)
+        
+    def test_set_container(self, _init_pygame, _display_surface_return_none, default_ui_manager):
+        test_container1 = UIContainer(relative_rect=pygame.Rect(100, 100, 300, 300), manager=default_ui_manager)
+        test_container2 = UIContainer(relative_rect=pygame.Rect(100, 100, 300, 300), manager=default_ui_manager)
+        element = UIElement(relative_rect=pygame.Rect(0, 0, 50, 50),
+                            manager=default_ui_manager,
+                            container=test_container1,
+                            starting_height=0,
+                            layer_thickness=1)
+        assert element.ui_container == test_container1
+        element.set_container(test_container2)
+        assert element.ui_container == test_container2
 
     def test_set_relative_position(self, _init_pygame, _display_surface_return_none, default_ui_manager):
         test_container = UIContainer(relative_rect=pygame.Rect(100, 100, 300, 300), manager=default_ui_manager)