首页 > 其他分享 >0062-Tui-表格示例

0062-Tui-表格示例

时间:2022-09-30 21:11:11浏览次数:85  
标签:mut 示例 self terminal Tui state let vec 0062

环境

  • Time 2022-08-16
  • Rust 1.63.0
  • Tui 0.18.0

前言

说明

参考:https://github.com/fdehau/tui-rs/blob/master/examples/table.rs

目标

使用 tui-rs 显示表格。

定义应用


struct App<'a> {
    state: TableState,
    items: Vec<Vec<&'a str>>,
}

impl<'a> App<'a> {
    fn new() -> App<'a> {
        App {
            state: TableState::default(),

            items: vec![
                vec!["阿法骨化醇软胶囊", "20.4", "5"],
                vec!["阿卡波糖胶囊", "9.6", "4"],
                vec!["阿仑膦酸钠片", "20.05", "7"],
                vec!["阿莫西林胶囊", "11.66", "2"],
                vec!["阿普仑片", "4.93", "6"],
                vec!["阿奇霉素胶囊", "15.3\n14.3", "1"],
                vec!["阿昔洛韦片", "5.46", "8"],
            ],
        }
    }
    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));
    }

    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));
    }
}

ui

fn ui<B: Backend>(frame: &mut Frame<B>, app: &mut App) {
    let chunks = Layout::default()
        .constraints([Constraint::Percentage(100)])
        .margin(5)
        .split(frame.size());

    let selected = Style::default().add_modifier(Modifier::REVERSED);
    let normal_style = Style::default().bg(Color::Blue);
    let header_cells = ["名称", "单价", "数量"]
        .iter()
        .map(|header| widgets::Cell::from(*header).style(Style::default().fg(Color::Red)));
    let header = widgets::Row::new(header_cells)
        .style(normal_style)
        .height(1)
        .bottom_margin(1);
    let rows = app.items.iter().map(|item| {
        let height = item
            .iter()
            .map(|content| content.chars().filter(|c| *c == '\n').count())
            .max()
            .unwrap_or_default()
            + 1;
        let cells = item.iter().map(|c| widgets::Cell::from(*c));
        widgets::Row::new(cells)
            .height(height as u16)
            .bottom_margin(1)
    });
    let t = widgets::Table::new(rows)
        .header(header)
        .block(Block::default().borders(Borders::ALL).title("Table"))
        .highlight_style(selected)
        .highlight_symbol(">> ")
        .widths(&[
            Constraint::Percentage(50),
            Constraint::Length(30),
            Constraint::Min(10),
        ]);
    frame.render_stateful_widget(t, chunks[0], &mut app.state);
}

效果展示

表格

总结

使用 tui-rs 渲染表格。

附录

源码

use anyhow::{Context, Result};
use crossterm::{event, terminal, ExecutableCommand};
use layout::{Constraint, Layout};
use style::{Color, Modifier, Style};
use tui::backend::{Backend, CrosstermBackend};
use tui::{layout, style, widgets, Frame, Terminal};
use widgets::{Block, Borders, TableState};

pub fn main() -> Result<()> {
    terminal::enable_raw_mode()?;
    let mut backend = CrosstermBackend::new(std::io::stdout());
    backend
        .execute(terminal::EnterAlternateScreen)?
        .execute(terminal::Clear(terminal::ClearType::All))?
        .hide_cursor()?;
    let mut terminal = tui::Terminal::new(backend)?;
    run(&mut terminal)?;
    terminal::disable_raw_mode()?;
    terminal
        .backend_mut()
        .execute(terminal::Clear(terminal::ClearType::All))?
        .execute(terminal::LeaveAlternateScreen)?
        .show_cursor()
        .context("重置控制台失败")
}

fn run<B: Backend>(terminal: &mut Terminal<B>) -> Result<()> {
    let timeout = std::time::Duration::from_millis(500);
    let mut app = App::new();
    loop {
        terminal.draw(|frame| ui(frame, &mut app))?;

        if event::poll(timeout)? {
            if let event::Event::Key(key) = event::read()? {
                use event::KeyCode::{self, Char, Esc};
                match key.code {
                    Char('q') | Char('Q') | Esc => return Ok(()),
                    KeyCode::Down => app.next(),
                    KeyCode::Up => app.previous(),
                    _ => {}
                }
            }
        }
    }
}

struct App<'a> {
    state: TableState,
    items: Vec<Vec<&'a str>>,
}

impl<'a> App<'a> {
    fn new() -> App<'a> {
        App {
            state: TableState::default(),

            items: vec![
                vec!["阿法骨化醇软胶囊", "20.4", "5"],
                vec!["阿卡波糖胶囊", "9.6", "4"],
                vec!["阿仑膦酸钠片", "20.05", "7"],
                vec!["阿莫西林胶囊", "11.66", "2"],
                vec!["阿普仑片", "4.93", "6"],
                vec!["阿奇霉素胶囊", "15.3\n14.3", "1"],
                vec!["阿昔洛韦片", "5.46", "8"],
            ],
        }
    }
    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));
    }

    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));
    }
}

fn ui<B: Backend>(frame: &mut Frame<B>, app: &mut App) {
    let chunks = Layout::default()
        .constraints([Constraint::Percentage(100)])
        .margin(5)
        .split(frame.size());

    let selected = Style::default().add_modifier(Modifier::REVERSED);
    let normal_style = Style::default().bg(Color::Blue);
    let header_cells = ["名称", "单价", "数量"]
        .iter()
        .map(|header| widgets::Cell::from(*header).style(Style::default().fg(Color::Red)));
    let header = widgets::Row::new(header_cells)
        .style(normal_style)
        .height(1)
        .bottom_margin(1);
    let rows = app.items.iter().map(|item| {
        let height = item
            .iter()
            .map(|content| content.chars().filter(|c| *c == '\n').count())
            .max()
            .unwrap_or_default()
            + 1;
        let cells = item.iter().map(|c| widgets::Cell::from(*c));
        widgets::Row::new(cells)
            .height(height as u16)
            .bottom_margin(1)
    });
    let t = widgets::Table::new(rows)
        .header(header)
        .block(Block::default().borders(Borders::ALL).title("Table"))
        .highlight_style(selected)
        .highlight_symbol(">> ")
        .widths(&[
            Constraint::Percentage(50),
            Constraint::Length(30),
            Constraint::Min(10),
        ]);
    frame.render_stateful_widget(t, chunks[0], &mut app.state);
}

标签:mut,示例,self,terminal,Tui,state,let,vec,0062
From: https://www.cnblogs.com/jiangbo4444/p/16746251.html

相关文章

  • 0063-Tui-页签示例
    环境Time2022-08-16Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/tabs.rs目标使用tui-rs显示页签。定义应用......
  • 0058-Tui-段落示例
    环境Time2022-08-12Rust1.63.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/paragraph.rs目标使用tui-rs显示段落。定义......
  • 0055-Tui-条形图示例
    环境Time2022-08-09Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/barchart.rs目标使用tui-rs显示条形图。第......
  • 0056-Tui-简单进度条
    环境Time2022-08-11Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/gauge.rs目标使用tui-rs显示进度条。定义数......
  • 0057-Tui-进度条示例
    环境Time2022-08-11Rust1.62.0Tui0.18.0前言说明参考:https://github.com/fdehau/tui-rs/blob/master/examples/gauge.rs目标使用tui-rs显示进度条。render......
  • 0049-Tui-创建控制台界面
    环境Time2022-08-08Rust1.62.0Tui0.18.0前言说明参考:https://docs.rs/tui/latest/tui/index.html目标使用tui-rs和crossterm启动一个控制台的终端界面。......
  • sanner格式以及示例
    格式:Scannerscanner=newScanner(System.in)“代码”Scanner.close(); 例:publicstaticvoidmain(String[]args){“”    //输入多个数字,并求其总和与平均......
  • Delphi XE MessageDialogAsync 和 MessageDialogSync [2] - 用法示例
    DelphiXEMessageDialogAsync和MessageDialogSync[2]-用法示例1、MessageDialogAsync//滔Roy2022.09.30usesFMX.Platform;//IFMXDialogServiceAsync......
  • C#使用CurrentUICulture切换语言
    C#使用CurrentUICulture切换语言-quanzhan-博客园(cnblogs.com)1、创建2个窗口   2、窗口1属性Localizable设置为True,Language选择英语(美国) 然后把窗口......
  • 秋色园QBlog技术原理解析:页面内容填充及多语言翻译流程演示示例(十)
    文章回顾:1:​​秋色园QBlog技术原理解析:开篇:整体认识(一)​​--介绍整体文件夹和文件的作用2:​​秋色园QBlog技术原理解析:认识整站处理流程(二)​​--介绍秋色园业务处理......