前言
本专栏是关于Rust的GUI库egui的部件讲解及应用实例分析,主要讲解egui的源代码、部件属性、如何应用。
环境配置
系统:windows
平台:visual studio code
语言:rust
库:egui、eframe
概述
本文是本专栏的第四篇博文,主要讲述滑动条部件的使用。
事实上,类似于iced,egui都提供了示例程序,本专栏的博文都是建立在官方示例程序以及源代码的基础上,进行的实例讲解。
即,本专栏的文章并非只是简单的翻译egui的官方示例与文档,而是针对于官方代码进行的实际使用,会在官方的代码上进行修改,包括解决一些问题。
系列博客链接:
1、<Rust>egui学习之小部件(一):如何在窗口及部件显示中文字符?
2、<Rust>egui学习之小部件(二):如何在egui窗口中添加按钮button以及标签label部件?
3、<Rust>egui学习之小部件(三):如何为窗口UI元件设置布局(间隔、水平、垂直排列)?
部件属性
有时候我们会需要在窗口设置滚动条,或者滑动条这样的部件,来实现滚动操作。在egui中,如果要添加滚动条,则使用ScrollArea部件,它表示的是创造一块区域,这个区域内显示滚动条操作,有两个方向,一个是水平滚动,一个是垂直滚动,可以单独设置,也可以都选择。
ScrollArea的官方定义:
rust
#[derive(Clone, Debug)]
#[must_use = "You should call .show()"]
pub struct ScrollArea {
/// Do we have horizontal/vertical scrolling enabled?
scroll_enabled: Vec2b,
auto_shrink: Vec2b,
max_size: Vec2,
min_scrolled_size: Vec2,
scroll_bar_visibility: ScrollBarVisibility,
id_source: Option<Id>,
offset_x: Option<f32>,
offset_y: Option<f32>,
/// If false, we ignore scroll events.
scrolling_enabled: bool,
drag_to_scroll: bool,
/// If true for vertical or horizontal the scroll wheel will stick to the
/// end position until user manually changes position. It will become true
/// again once scroll handle makes contact with end.
stick_to_end: Vec2b,
/// If false, `scroll_to_*` functions will not be animated
animated: bool,
}
添加滚动条区域
rust
egui::ScrollArea::both().enable_scrolling(true)
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
.show_rows(ui,row_height,total_rows,|ui,rowrange|{
ui.horizontal(|ui|{
for i in 0..8{
ui.label(format!("label{}",i));
}
});
ui.vertical(|ui|{
for i in 0..10{
ui.label(format!("label{}",i));
}
})
});
如上图,滚动条在窗口中作为部件显示,其显示区域可以通过布局调整。正常来说,我们只需要滚动条的拖动功能,即无需其状态反馈。
但如果需要也可以设置,ScrollArea有State属性,用于接受对ScrollArea操作时的状态反馈:
rust
let sc1=egui::ScrollArea::both().enable_scrolling(true)
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded)
.max_height(200.0)
.show_rows(ui,row_height,total_rows,|ui,rowrange|{
ui.set_height(200.0);
ui.set_width(100.0);
ui.horizontal(|ui|{
for i in 0..8{
ui.label(format!("label{}",i));
}
});
ui.vertical(|ui|{
for i in 0..10{
ui.label(format!("label{}",i));
}
})
});
ui.label(format!("scroll area:{}",sc1.state.offset.x));
ui.label(format!("scroll area:{}",sc1.state.offset.y));
如上,我们添加两个标签,用于显示滚动条滑动时滑块的移动量:
State参数如下:
rust
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct State {
/// Positive offset means scrolling down/right
pub offset: Vec2,
/// If set, quickly but smoothly scroll to this target offset.
offset_target: [Option<ScrollTarget>; 2],
/// Were the scroll bars visible last frame?
show_scroll: Vec2b,
/// The content were to large to fit large frame.
content_is_too_large: Vec2b,
/// Did the user interact (hover or drag) the scroll bars last frame?
scroll_bar_interaction: Vec2b,
/// Momentum, used for kinetic scrolling
#[cfg_attr(feature = "serde", serde(skip))]
vel: Vec2,
/// Mouse offset relative to the top of the handle when started moving the handle.
scroll_start_offset_from_top_left: [Option<f32>; 2],
/// Is the scroll sticky. This is true while scroll handle is in the end position
/// and remains that way until the user moves the scroll_handle. Once unstuck (false)
/// it remains false until the scroll touches the end position, which reenables stickiness.
scroll_stuck_to_end: Vec2b,
/// Area that can be dragged. This is the size of the content from the last frame.
interact_rect: Option<Rect>,
}
如果要设置其样式,那么我们需要设置其Style。
但ScrollArea并没有单独的Style设置,不过可以通用的Style进行设置,可以修改字体尺寸和字体样式:
rust
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct Style {
/// If set this will change the default [`TextStyle`] for all widgets.
///
/// On most widgets you can also set an explicit text style,
/// which will take precedence over this.
pub override_text_style: Option<TextStyle>,
/// If set this will change the font family and size for all widgets.
///
/// On most widgets you can also set an explicit text style,
/// which will take precedence over this.
pub override_font_id: Option<FontId>,
/// The [`FontFamily`] and size you want to use for a specific [`TextStyle`].
///
/// The most convenient way to look something up in this is to use [`TextStyle::resolve`].
///
/// If you would like to overwrite app `text_styles`
///
/// ```
/// # let mut ctx = egui::Context::default();
/// use egui::FontFamily::Proportional;
/// use egui::FontId;
/// use egui::TextStyle::*;
///
/// // Get current context style
/// let mut style = (*ctx.style()).clone();
///
/// // Redefine text_styles
/// style.text_styles = [
/// (Heading, FontId::new(30.0, Proportional)),
/// (Name("Heading2".into()), FontId::new(25.0, Proportional)),
/// (Name("Context".into()), FontId::new(23.0, Proportional)),
/// (Body, FontId::new(18.0, Proportional)),
/// (Monospace, FontId::new(14.0, Proportional)),
/// (Button, FontId::new(14.0, Proportional)),
/// (Small, FontId::new(10.0, Proportional)),
/// ].into();
///
/// // Mutate global style with above changes
/// ctx.set_style(style);
/// ```
pub text_styles: BTreeMap<TextStyle, FontId>,
/// The style to use for [`DragValue`] text.
pub drag_value_text_style: TextStyle,
/// How to format numbers as strings, e.g. in a [`crate::DragValue`].
///
/// You can override this to e.g. add thousands separators.
#[cfg_attr(feature = "serde", serde(skip))]
pub number_formatter: NumberFormatter,
/// If set, labels, buttons, etc. will use this to determine whether to wrap the text at the
/// right edge of the [`Ui`] they are in. By default, this is `None`.
///
/// **Note**: this API is deprecated, use `wrap_mode` instead.
///
/// * `None`: use `wrap_mode` instead
/// * `Some(true)`: wrap mode defaults to [`crate::TextWrapMode::Wrap`]
/// * `Some(false)`: wrap mode defaults to [`crate::TextWrapMode::Extend`]
#[deprecated = "Use wrap_mode instead"]
pub wrap: Option<bool>,
/// If set, labels, buttons, etc. will use this to determine whether to wrap or truncate the
/// text at the right edge of the [`Ui`] they are in, or to extend it. By default, this is
/// `None`.
///
/// * `None`: follow layout (with may wrap)
/// * `Some(mode)`: use the specified mode as default
pub wrap_mode: Option<crate::TextWrapMode>,
/// Sizes and distances between widgets
pub spacing: Spacing,
/// How and when interaction happens.
pub interaction: Interaction,
/// Colors etc.
pub visuals: Visuals,
/// How many seconds a typical animation should last.
pub animation_time: f32,
/// Options to help debug why egui behaves strangely.
///
/// Only available in debug builds.
#[cfg(debug_assertions)]
pub debug: DebugOptions,
/// Show tooltips explaining [`DragValue`]:s etc when hovered.
///
/// This only affects a few egui widgets.
pub explanation_tooltips: bool,
/// Show the URL of hyperlinks in a tooltip when hovered.
pub url_in_tooltip: bool,
/// If true and scrolling is enabled for only one direction, allow horizontal scrolling without pressing shift
pub always_scroll_the_only_direction: bool,
}
但好像没有修改背景颜色、修改滑块样式这些选项,可自定义的还是比较少。但是如果只想要修改文字样式,那么可以针对label部件单独设置,可以适应Richtext来创建标签文本,那么就可以设置颜色、背景色、下划线等多种自定义样式:
rust
ui.label(RichText::new(format!("标签{}",i))
.color(Color32::from_rgb(0, 0, 0)).underline()
.strikethrough()
.background_color(Color32::from_rgb(255, 0, 255)));