首页 > 其他分享 >0063-Tui-页签示例

0063-Tui-页签示例

时间:2022-09-30 21:11:04浏览次数:81  
标签:index 示例 default mut self title Tui let 0063

环境

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

前言

说明

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

目标

使用 tui-rs 显示页签。

定义应用

struct App<'a> {
    pub titles: Vec<&'a str>,
    pub index: usize,
}

impl<'a> App<'a> {
    fn new() -> App<'a> {
        App {
            titles: vec!["唐", "宋", "元", "明"],
            index: 0,
        }
    }

    pub fn next(&mut self) {
        self.index = (self.index + 1) % self.titles.len();
    }

    pub fn previous(&mut self) {
        if self.index > 0 {
            self.index -= 1;
        } else {
            self.index = self.titles.len() - 1;
        }
    }
}

ui

fn ui<B: Backend>(frame: &mut Frame<B>, app: &mut App) {
    let size = frame.size();
    let chunks = Layout::default()
        .direction(layout::Direction::Vertical)
        .margin(5)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(size);

    let block = Block::default().style(Style::default().bg(Color::White).fg(Color::Black));
    frame.render_widget(block, size);
    let titles = app
        .titles
        .iter()
        .map(|&title| {
            text::Spans::from(vec![text::Span::styled(
                title,
                Style::default().fg(Color::Yellow),
            )])
        })
        .collect();
    let tabs = Tabs::new(titles)
        .block(Block::default().borders(Borders::ALL).title("页签"))
        .select(app.index)
        .style(Style::default().fg(Color::Cyan))
        .highlight_style(
            Style::default()
                .add_modifier(Modifier::BOLD)
                .bg(Color::Black),
        );
    frame.render_widget(tabs, chunks[0]);
    let inner = match app.index {
        0 => Block::default().title("唐诗").borders(Borders::ALL),
        1 => Block::default().title("宋词").borders(Borders::ALL),
        2 => Block::default().title("元曲").borders(Borders::ALL),
        3 => Block::default().title("明小说").borders(Borders::ALL),
        _ => unreachable!(),
    };
    frame.render_widget(inner, chunks[1]);
}

效果展示

页签

总结

使用 tui-rs 渲染页签。

附录

源码

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

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::Right => app.next(),
                    KeyCode::Left => app.previous(),
                    _ => {}
                }
            }
        }
    }
}

struct App<'a> {
    pub titles: Vec<&'a str>,
    pub index: usize,
}

impl<'a> App<'a> {
    fn new() -> App<'a> {
        App {
            titles: vec!["唐", "宋", "元", "明"],
            index: 0,
        }
    }

    pub fn next(&mut self) {
        self.index = (self.index + 1) % self.titles.len();
    }

    pub fn previous(&mut self) {
        if self.index > 0 {
            self.index -= 1;
        } else {
            self.index = self.titles.len() - 1;
        }
    }
}

fn ui<B: Backend>(frame: &mut Frame<B>, app: &mut App) {
    let size = frame.size();
    let chunks = Layout::default()
        .direction(layout::Direction::Vertical)
        .margin(5)
        .constraints([Constraint::Length(3), Constraint::Min(0)])
        .split(size);

    let block = Block::default().style(Style::default().bg(Color::White).fg(Color::Black));
    frame.render_widget(block, size);
    let titles = app
        .titles
        .iter()
        .map(|&title| {
            text::Spans::from(vec![text::Span::styled(
                title,
                Style::default().fg(Color::Yellow),
            )])
        })
        .collect();
    let tabs = Tabs::new(titles)
        .block(Block::default().borders(Borders::ALL).title("页签"))
        .select(app.index)
        .style(Style::default().fg(Color::Cyan))
        .highlight_style(
            Style::default()
                .add_modifier(Modifier::BOLD)
                .bg(Color::Black),
        );
    frame.render_widget(tabs, chunks[0]);
    let inner = match app.index {
        0 => Block::default().title("唐诗").borders(Borders::ALL),
        1 => Block::default().title("宋词").borders(Borders::ALL),
        2 => Block::default().title("元曲").borders(Borders::ALL),
        3 => Block::default().title("明小说").borders(Borders::ALL),
        _ => unreachable!(),
    };
    frame.render_widget(inner, chunks[1]);
}

标签:index,示例,default,mut,self,title,Tui,let,0063
From: https://www.cnblogs.com/jiangbo4444/p/16746255.html

相关文章

  • 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技术原理解析:认识整站处理流程(二)​​--介绍秋色园业务处理......
  • MarkDown 使用说明示例
    一、标题一级标题二级标题三级标题四级标题五级标题六级标题一级标题这是H2这是H3一级和二级标题还有一种写法就是下面加横杆,同时超过2个的=和-都可以有效果。This......