<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

相关文章

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Rust中的注释使用解读

《Rust中的注释使用解读》本文介绍了Rust中的行注释、块注释和文档注释的使用方法,通过示例展示了如何在实际代码中应用这些注释,以提高代码的可读性和可维护性... 目录Rust 中的注释使用指南1. 行注释示例:行注释2. 块注释示例:块注释3. 文档注释示例:文档注释4. 综合示例总结Rust 中的注释

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式

Rust中的Drop特性之解读自动化资源清理的魔法

《Rust中的Drop特性之解读自动化资源清理的魔法》Rust通过Drop特性实现了自动清理机制,确保资源在对象超出作用域时自动释放,避免了手动管理资源时可能出现的内存泄漏或双重释放问题,智能指针如B... 目录自动清理机制:Rust 的析构函数提前释放资源:std::mem::drop android的妙

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

在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使用场景场景一:函数返回可能不存在的值场景