<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

相关文章

Windows的CMD窗口如何查看并杀死nginx进程

《Windows的CMD窗口如何查看并杀死nginx进程》:本文主要介绍Windows的CMD窗口如何查看并杀死nginx进程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows的CMD窗口查看并杀死nginx进程开启nginx查看nginx进程停止nginx服务

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

使用WPF实现窗口抖动动画效果

《使用WPF实现窗口抖动动画效果》在用户界面设计中,适当的动画反馈可以提升用户体验,尤其是在错误提示、操作失败等场景下,窗口抖动作为一种常见且直观的视觉反馈方式,常用于提醒用户注意当前状态,本文将详细... 目录前言实现思路概述核心代码实现1、 获取目标窗口2、初始化基础位置值3、创建抖动动画4、动画完成后

重新对Java的类加载器的学习方式

《重新对Java的类加载器的学习方式》:本文主要介绍重新对Java的类加载器的学习方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、介绍1.1、简介1.2、符号引用和直接引用1、符号引用2、直接引用3、符号转直接的过程2、加载流程3、类加载的分类3.1、显示

rust 中的 EBNF简介举例

《rust中的EBNF简介举例》:本文主要介绍rust中的EBNF简介举例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 什么是 EBNF?2. 核心概念3. EBNF 语法符号详解4. 如何阅读 EBNF 规则5. 示例示例 1:简单的电子邮件地址

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

Java学习手册之Filter和Listener使用方法

《Java学习手册之Filter和Listener使用方法》:本文主要介绍Java学习手册之Filter和Listener使用方法的相关资料,Filter是一种拦截器,可以在请求到达Servl... 目录一、Filter(过滤器)1. Filter 的工作原理2. Filter 的配置与使用二、Listen

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

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

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