|
87 | 87 | } |
88 | 88 |
|
89 | 89 |
|
| 90 | +class NotAContainer(Exception): |
| 91 | + """Exception raised if you attempt to add a child to a widget which doesn't permit child nodes.""" |
| 92 | + |
| 93 | + |
90 | 94 | _NULL_STYLE = Style() |
91 | 95 |
|
92 | 96 |
|
@@ -264,6 +268,9 @@ class Widget(DOMNode): |
264 | 268 | BORDER_SUBTITLE: ClassVar[str] = "" |
265 | 269 | """Initial value for border_subtitle attribute.""" |
266 | 270 |
|
| 271 | + ALLOW_CHILDREN: ClassVar[bool] = True |
| 272 | + """Set to `False` to prevent adding children to this widget.""" |
| 273 | + |
267 | 274 | can_focus: bool = False |
268 | 275 | """Widget may receive focus.""" |
269 | 276 | can_focus_children: bool = True |
@@ -488,6 +495,21 @@ def tooltip(self, tooltip: RenderableType | None): |
488 | 495 | except NoScreen: |
489 | 496 | pass |
490 | 497 |
|
| 498 | + def compose_add_child(self, widget: Widget) -> None: |
| 499 | + """Add a node to children. |
| 500 | +
|
| 501 | + This is used by the compose process when it adds children. |
| 502 | + There is no need to use it directly, but you may want to override it in a subclass |
| 503 | + if you want children to be attached to a different node. |
| 504 | +
|
| 505 | + Args: |
| 506 | + widget: A Widget to add. |
| 507 | + """ |
| 508 | + _rich_traceback_omit = True |
| 509 | + if not self.ALLOW_CHILDREN: |
| 510 | + raise NotAContainer(f"Can't add children to {type(widget)} widgets") |
| 511 | + self._nodes._append(widget) |
| 512 | + |
491 | 513 | def __enter__(self) -> Self: |
492 | 514 | """Use as context manager when composing.""" |
493 | 515 | self.app._compose_stacks[-1].append(self) |
|
0 commit comments