<Rust>egui学习之小部件(四):如何在窗口中添加滑动条部件?

2024-08-29 11:52

本文主要是介绍<Rust>egui学习之小部件(四):如何在窗口中添加滑动条部件?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言
本专栏是关于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的官方定义:

#[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 animatedanimated: bool,
}
添加滚动条区域
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操作时的状态反馈:

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参数如下:

#[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/rightpub 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进行设置,可以修改字体尺寸和字体样式:

#[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 defaultpub wrap_mode: Option<crate::TextWrapMode>,/// Sizes and distances between widgetspub 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 shiftpub always_scroll_the_only_direction: bool,
}

但好像没有修改背景颜色、修改滑块样式这些选项,可自定义的还是比较少。但是如果只想要修改文字样式,那么可以针对label部件单独设置,可以适应Richtext来创建标签文本,那么就可以设置颜色、背景色、下划线等多种自定义样式:

ui.label(RichText::new(format!("标签{}",i)).color(Color32::from_rgb(0, 0, 0)).underline().strikethrough().background_color(Color32::from_rgb(255, 0, 255)));

在这里插入图片描述

这篇关于<Rust>egui学习之小部件(四):如何在窗口中添加滑动条部件?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1117784

相关文章

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

浅析Rust多线程中如何安全的使用变量

《浅析Rust多线程中如何安全的使用变量》这篇文章主要为大家详细介绍了Rust如何在线程的闭包中安全的使用变量,包括共享变量和修改变量,文中的示例代码讲解详细,有需要的小伙伴可以参考下... 目录1. 向线程传递变量2. 多线程共享变量引用3. 多线程中修改变量4. 总结在Rust语言中,一个既引人入胜又可

Rust 数据类型详解

《Rust数据类型详解》本文介绍了Rust编程语言中的标量类型和复合类型,标量类型包括整数、浮点数、布尔和字符,而复合类型则包括元组和数组,标量类型用于表示单个值,具有不同的表示和范围,本文介绍的非... 目录一、标量类型(Scalar Types)1. 整数类型(Integer Types)1.1 整数字

Rust中的Option枚举快速入门教程

《Rust中的Option枚举快速入门教程》Rust中的Option枚举用于表示可能不存在的值,提供了多种方法来处理这些值,避免了空指针异常,文章介绍了Option的定义、常见方法、使用场景以及注意事... 目录引言Option介绍Option的常见方法Option使用场景场景一:函数返回可能不存在的值场景

bat脚本启动git bash窗口,并执行命令方式

《bat脚本启动gitbash窗口,并执行命令方式》本文介绍了如何在Windows服务器上使用cmd启动jar包时出现乱码的问题,并提供了解决方法——使用GitBash窗口启动并设置编码,通过编写s... 目录一、简介二、使用说明2.1 start.BAT脚本2.2 参数说明2.3 效果总结一、简介某些情

基于Redis有序集合实现滑动窗口限流的步骤

《基于Redis有序集合实现滑动窗口限流的步骤》滑动窗口算法是一种基于时间窗口的限流算法,通过动态地滑动窗口,可以动态调整限流的速率,Redis有序集合可以用来实现滑动窗口限流,本文介绍基于Redis... 滑动窗口算法是一种基于时间窗口的限流算法,它将时间划分为若干个固定大小的窗口,每个窗口内记录了该时间

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;