Understanding the hierarchy of the UI
There are certain rules and requirements to create a user interface; in its most fundamental form, the UI is just a collection of rectangles contained within other rectangles. This recipe will discuss how the hierarchy of controls is linked together.
How to do it…
You need to perform the following steps:
- Let's start by defining the top-level window that resides at the top of the hierarchy:
class MyFrame(wx.Frame): def __init__(self, parent, title=""): super(MyFrame, self).__init__(parent, title=title) self.panel = MyPanel(self)
- Next, let's define the
Panel
class, which will serve as the general container for user controls and give it a child control through the following code:class MyPanel(wx.Panel): def __init__(self, parent): super(MyPanel, self).__init__(parent) self.button = wx.Button(self, label="Push Me")
How it works…
All controls have an argument for a parent in their constructor. The parent is the container that the child control belongs to; so, in the first snippet when the MyPanel
object was created, it was passed into the Frame
object as its parent. This caused the panel rectangle to be placed inside of the rectangle of the Frame
object. Then again, inside of the MyPanel
object, a Button
object was created with Panel
as the parent, which instructed the button rectangle to be positioned inside the area owned by Panel
.
There are three layers of containment in the window hierarchy for different categories of control types:
- Top-level Windows (Frames and Dialogs): These cannot be contained by any type of container when displayed on screen. They are always at the top of the visual hierarchy.
- General Containers (Panels, Notebooks, and so on): These are general container windows that serve the purpose of grouping other controls together and providing layout. They can contain other general containers or controls.
- Controls (Buttons, CheckBoxes, ComboBoxes, and so on): These are user controls that cannot contain any other controls. They are the leaves at the bottom of the tree.
There's more…
When building an application with a user interface, this hierarchy is important to remember as it plays a critical role in how the layout and design of the interface is performed. Most notably, in the middle general containers layer, the nesting and composition of the control layout in combination with event handling can lead to unexpected issues if this hierarchy is forgotten. So, just remember this tree structure when building out your application's interface:
See also
- The Controlling the propagation of events recipe in this chapter explains the way this hierarchy affects how events are reported.