Psionman
Psionman

Reputation: 3677

How can I remove a StaticBox in wxPython?

I have an application in which I wish to remove all of the widgets in a sizer. This works except for the StaticBox which stubbornly remains. What can I do? It doesn't seem to behave as a sizer, nor a normal widget.

import wx

class MainFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        super().__init__(None, *args, **kwargs)

        self.panel = MainPanel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.panel)
        self.SetSizer(sizer)
        self.Center()
        self.Show()


class MainPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)

        self.widget_sizer = self._widget_sizer()
        cmd_clear = wx.Button(self, id=wx.ID_CLEAR)
        cmd_clear.Bind(wx.EVT_BUTTON, self.clear_widgets)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.widget_sizer)
        sizer.Add(cmd_clear)
        self.SetSizer(sizer)

    def clear_widgets(self, event):
        self._delete_widgets(self.widget_sizer)

    def _widget_sizer(self):
        txt_test = wx.TextCtrl(self)

        test_box = wx.StaticBox(parent=self, label="Box Label")
        test_sizer = wx.StaticBoxSizer(box=test_box, orient=wx.VERTICAL)
        chk_test = wx.CheckBox(self, label='Check test')
        test_sizer.Add(chk_test)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(txt_test)
        sizer.Add(test_sizer)
        return sizer

    def _delete_widgets(self, sizer):
        for child in sizer.GetChildren():
            if child.IsSizer():
                self._delete_widgets(child.GetSizer())
            else:
                child.GetWindow().Destroy()

if __name__ == '__main__':
        wx_app = wx.App()
        MainFrame()
        wx_app.MainLoop()

Upvotes: 0

Views: 143

Answers (1)

ArdeaCinerea
ArdeaCinerea

Reputation: 36

I look at your code using wx.lib.inspection.InspectionTool and it seems that the staticBox is not a child from your sizer.

The StaticBox remains because its parent is your MainPanel.

I tried different way of creating the StaticBox (including letting it be created by the BoxSizer itself and then adding it "manually" to the Sizer with test_sizer.Add(test_sizer.GetStaticBox()) but it doesn't work:

wx._core.wxAssertionError: C++ assertion ""!m_containingSizer"" failed at /home/wxpy/wxPython-4.1.0/ext/wxWidgets/src/common/wincmn.cpp(2490) in SetContainingSizer(): Adding a window already in a sizer, detach it first!

The BoxSizer always stays "attached" to the panel as a child and is never an instance of SizerItem.

It is a bit weird... It looks like a bug to me. It might be worth reporting it.

The only workaround i see for you to delete it is to access it separately using: panel.GetChildren() and test if child as the proper name or maybe by id...

Upvotes: 1

Related Questions