pub trait Widget {
// Required method
fn render(self, area: Rect, buf: &mut Buffer)
where Self: Sized;
}
Expand description
A Widget
is a type that can be drawn on a Buffer
in a given Rect
.
Prior to Ratatui 0.26.0, widgets generally were created for each frame as they were consumed during rendering. This meant that they were not meant to be stored but used as commands to draw common figures in the UI.
Starting with Ratatui 0.26.0, all the internal widgets implement Widget for a reference to themselves. This allows you to store a reference to a widget and render it later. Widget crates should consider also doing this to allow for more flexibility in how widgets are used.
In Ratatui 0.26.0, we also added an unstable WidgetRef
trait and implemented this on all the
internal widgets. In addition to the above benefit of rendering references to widgets, this also
allows you to render boxed widgets. This is useful when you want to store a collection of
widgets with different types. You can then iterate over the collection and render each widget.
See https://github.com/ratatui/ratatui/issues/1287 for more information.
In general where you expect a widget to immutably work on its data, we recommended to implement
Widget
for a reference to the widget (impl Widget for &MyWidget
). If you need to store state
between draw calls, implement StatefulWidget
if you want the Widget to be immutable, or
implement Widget
for a mutable reference to the widget (impl Widget for &mut MyWidget
) if
you want the widget to be mutable. The mutable widget pattern is used infrequently in apps, but
can be quite useful.
A blanket implementation of Widget
for &W
where W
implements WidgetRef
is provided.
Widget is also implemented for &str
and String
types.
§Examples
use ratatui::{
backend::TestBackend,
widgets::{Clear, Widget},
Terminal,
};
terminal.draw(|frame| {
frame.render_widget(Clear, frame.area());
});
It’s common to render widgets inside other widgets:
use ratatui::{buffer::Buffer, layout::Rect, text::Line, widgets::Widget};
struct MyWidget;
impl Widget for MyWidget {
fn render(self, area: Rect, buf: &mut Buffer) {
Line::raw("Hello").render(area, buf);
}
}
Required Methods§
Implementations on Foreign Types§
Source§impl Widget for &str
impl Widget for &str
Renders a string slice as a widget.
This implementation allows a string slice (&str
) to act as a widget, meaning it can be drawn
onto a Buffer
in a specified Rect
. The slice represents a static string which can be
rendered by reference, thereby avoiding the need for string cloning or ownership transfer when
drawing the text to the screen.