Struct ratatui::widgets::TableState

source ·
pub struct TableState { /* private fields */ }
Expand description

State of a Table widget

This state can be used to scroll through the rows and select one of them. When the table is rendered as a stateful widget, the selected row will be highlighted and the table will be shifted to ensure that the selected row is visible. This will modify the TableState object passed to the Frame::render_stateful_widget method.

The state consists of two fields:

  • offset: the index of the first row to be displayed
  • selected: the index of the selected row, which can be None if no row is selected

See the table`` example and the recipe and `traceroute tabs in the demo2 example in the Examples directory for a more in depth example of the various configuration options and for how to handle state.

§Example

let table = Table::new(rows, widths).widths(widths);

// Note: TableState should be stored in your application state (not constructed in your render
// method) so that the selected row is preserved across renders
let mut table_state = TableState::default();
*table_state.offset_mut() = 1; // display the second row and onwards
table_state.select(Some(3)); // select the forth row (0-indexed)

frame.render_stateful_widget(table, area, &mut table_state);

Note that if Table::widths is not called before rendering, the rendered columns will have equal width.

Implementations§

source§

impl TableState

source

pub const fn new() -> Self

Creates a new TableState

§Examples
let state = TableState::new();
source

pub const fn with_offset(self, offset: usize) -> Self

Sets the index of the first row to be displayed

This is a fluent setter method which must be chained or used as it consumes self

§Examples
let state = TableState::new().with_offset(1);
source

pub fn with_selected<T>(self, selected: T) -> Self
where T: Into<Option<usize>>,

Sets the index of the selected row

This is a fluent setter method which must be chained or used as it consumes self

§Examples
let state = TableState::new().with_selected(Some(1));
Examples found in repository?
examples/table.rs (line 104)
101
102
103
104
105
106
107
108
109
110
111
    fn new() -> Self {
        let data_vec = generate_fake_names();
        Self {
            state: TableState::default().with_selected(0),
            longest_item_lens: constraint_len_calculator(&data_vec),
            scroll_state: ScrollbarState::new((data_vec.len() - 1) * ITEM_HEIGHT),
            colors: TableColors::new(&PALETTES[0]),
            color_index: 0,
            items: data_vec,
        }
    }
More examples
Hide additional examples
examples/demo2/tabs/recipe.rs (line 151)
150
151
152
153
154
155
156
157
158
159
160
161
162
163
fn render_ingredients(selected_row: usize, area: Rect, buf: &mut Buffer) {
    let mut state = TableState::default().with_selected(Some(selected_row));
    let rows = INGREDIENTS.iter().copied();
    let theme = THEME.recipe;
    StatefulWidget::render(
        Table::new(rows, [Constraint::Length(7), Constraint::Length(30)])
            .block(Block::new().style(theme.ingredients))
            .header(Row::new(vec!["Qty", "Ingredient"]).style(theme.ingredients_header))
            .highlight_style(Style::new().light_yellow()),
        area,
        buf,
        &mut state,
    );
}
examples/demo2/tabs/traceroute.rs (line 47)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
fn render_hops(selected_row: usize, area: Rect, buf: &mut Buffer) {
    let mut state = TableState::default().with_selected(Some(selected_row));
    let rows = HOPS
        .iter()
        .map(|hop| Row::new(vec![hop.host, hop.address]))
        .collect_vec();
    let block = Block::new()
        .padding(Padding::new(1, 1, 1, 1))
        .title_alignment(Alignment::Center)
        .title("Traceroute bad.horse".bold().white());
    StatefulWidget::render(
        Table::new(rows, [Constraint::Max(100), Constraint::Length(15)])
            .header(Row::new(vec!["Host", "Address"]).set_style(THEME.traceroute.header))
            .highlight_style(THEME.traceroute.selected)
            .block(block),
        area,
        buf,
        &mut state,
    );
    let mut scrollbar_state = ScrollbarState::default()
        .content_length(HOPS.len())
        .position(selected_row);
    let area = Rect {
        width: area.width + 1,
        y: area.y + 3,
        height: area.height - 4,
        ..area
    };
    Scrollbar::default()
        .orientation(ScrollbarOrientation::VerticalLeft)
        .begin_symbol(None)
        .end_symbol(None)
        .track_symbol(None)
        .thumb_symbol("▌")
        .render(area, buf, &mut scrollbar_state);
}
source

pub const fn offset(&self) -> usize

Index of the first row to be displayed

§Examples
let state = TableState::new();
assert_eq!(state.offset(), 0);
source

pub fn offset_mut(&mut self) -> &mut usize

Mutable reference to the index of the first row to be displayed

§Examples
let mut state = TableState::default();
*state.offset_mut() = 1;
source

pub const fn selected(&self) -> Option<usize>

Index of the selected row

Returns None if no row is selected

§Examples
let state = TableState::new();
assert_eq!(state.selected(), None);
Examples found in repository?
examples/table.rs (line 113)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    pub fn next(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i >= self.items.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
        self.scroll_state = self.scroll_state.position(i * ITEM_HEIGHT);
    }

    pub fn previous(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i == 0 {
                    self.items.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
        self.scroll_state = self.scroll_state.position(i * ITEM_HEIGHT);
    }
source

pub fn selected_mut(&mut self) -> &mut Option<usize>

Mutable reference to the index of the selected row

Returns None if no row is selected

§Examples
let mut state = TableState::default();
*state.selected_mut() = Some(1);
source

pub fn select(&mut self, index: Option<usize>)

Sets the index of the selected row

Set to None if no row is selected. This will also reset the offset to 0.

§Examples
let mut state = TableState::default();
state.select(Some(1));
Examples found in repository?
examples/table.rs (line 123)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    pub fn next(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i >= self.items.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
        self.scroll_state = self.scroll_state.position(i * ITEM_HEIGHT);
    }

    pub fn previous(&mut self) {
        let i = match self.state.selected() {
            Some(i) => {
                if i == 0 {
                    self.items.len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.state.select(Some(i));
        self.scroll_state = self.scroll_state.position(i * ITEM_HEIGHT);
    }

Trait Implementations§

source§

impl Clone for TableState

source§

fn clone(&self) -> TableState

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for TableState

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for TableState

source§

fn default() -> TableState

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for TableState

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl Hash for TableState

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq for TableState

source§

fn eq(&self, other: &TableState) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Serialize for TableState

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Eq for TableState

source§

impl StructuralPartialEq for TableState

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,