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

news2024/9/21 7:59:20

前言
本专栏是关于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 animated
    animated: 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/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进行设置,可以修改字体尺寸和字体样式:

#[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来创建标签文本,那么就可以设置颜色、背景色、下划线等多种自定义样式:

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2092502.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++ Primer Plus习题】7.10

问题: 解答: #include <iostream> using namespace std;double add(double a, double b) {return a b; }double mul(double a, double b) {return a * b; }double sub(double a, double b) {return a - b; }double div(double a, double b) {return a / b; }double cal…

[LLM]:大模型(Transformer)参数量分析

1. 前言2. 模型参数量 文章内容主要摘自&#xff1a;https://zhuanlan.zhihu.com/p/624740065 1. 前言 最近&#xff0c;OpenAI推出的ChatGPT展现出了卓越的性能&#xff0c;引发了大语言模型(Large Language Model, LLM)的研究热潮。大规模语言模型的“大”体现在两个方面&am…

Python编码系列—Python代码重构:提升代码质量

&#x1f31f;&#x1f31f; 欢迎来到我的技术小筑&#xff0c;一个专为技术探索者打造的交流空间。在这里&#xff0c;我们不仅分享代码的智慧&#xff0c;还探讨技术的深度与广度。无论您是资深开发者还是技术新手&#xff0c;这里都有一片属于您的天空。让我们在知识的海洋中…

Leetcode面试经典150题-151.反转字符串中的单词

class Solution {public String reverseWords(String s) {/**先trim一下去掉前后的空格*/String str s.trim();/**转成字符数组 */char[] sArr str.toCharArray();/**先整体倒置*/int l 0;int r sArr.length - 1;reverse(sArr, l, r);/**然后每个单词中逆序 */int left 0;…

SAM 提示框和 Unet的语义分割的融合:自动驾驶车道线分割

1、前言 最近SAM 模型复现的多了&#xff0c;看了不少官方的源码&#xff0c;尝试下SAM和Unet的结合 SAM的提示分割&#xff0c;其实就是在分割的时候&#xff0c;为数据增加一个提示信息&#xff0c;可以是框&#xff0c;点&#xff0c;或者文本等等。这样大模型网络就可以根…

【Python】简单的爬虫抓取

效果&#xff1a;抓取某个学校网站的教授名录&#xff0c;并获取研究方向。 由于网站使用的都是明文&#xff0c;所以抓起来没什么难度&#xff0c;且平时访问量小&#xff0c;很值得用来练习。 代码如下&#xff0c;解释请见注释 import timeimport requests from bs4 impor…

RN开发问题

1、滚动项定位错误 ERROR Invariant Violation: scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, otherwise there is no way to know the location of offscreen indices or handle failures. 原因&#xff1a;已修复&#xff0c…

求一个使用C语言将重力加速度gx,gy,gz积分获取到速度的代码

&#x1f3c6;本文收录于《CSDN问答解惑-专业版》专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收…

完整指南:CNStream流处理多路并发框架适配到NVIDIA Jetson Orin (一) 依赖库编译、第三方库编译安装

目录 1 jetson-ffmpeg的编译安装与配置--用来做视频编码、视频解码 2 CV-CUDA库的编译安装与配置--用来做图像缩放、裁剪、色域转换 3 cuda cudnn TensorRT相关库的拷贝与配置 3.1将cuda cudnn TensorRT相关的头文件拷贝到工程中 3.2 将cuda cudnn TensorRT相关的库拷贝到…

docker实战基础一

一、docker安装 # step 1: 安装必要的一些系统工具 yum install -y yum-utils device-mapper-persistent-data lvm2 # Step 2: 添加软件源信息 yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo # Step 3: 更新并安装 Doc…

FlowUs:强大图表功能与多维表结合,开启便捷办公新时代

在当今数字化办公的浪潮中&#xff0c;我们一直在寻找一款能够高效整合数据、清晰呈现信息的工具。而 FlowUs 以其强大的图表功能结合多维表的能力&#xff0c;为我们带来了前所未有的便捷体验。 一、多维表&#xff1a;数据管理的强大基石 FlowUs 的多维表功能就像是一个数据魔…

016_Save_the_picture_in_Matlab中保存图片

图片文件 Matlab核心功能包括出图&#xff0c;印刷质量的图片输出是Matlab核心竞争力之一&#xff0c;matplotlib疯狂追赶&#xff0c;但还是差距明显。出图的含义就是&#xff1a;打印或者导出图形窗体的内容&#xff0c;可供后续使用。在Matlab中&#xff0c;这个行为被定义…

弗洛伊德(Floyd)算法(C/C++)

弗洛伊德算法&#xff08;Floyds algorithm&#xff09;&#xff0c;又称为弗洛伊德-沃尔什算法&#xff08;Floyd-Warshall algorithm&#xff09;&#xff0c;是一种用于在加权图中找到所有顶点对之间最短路径的算法。这个算法适用于有向图和无向图&#xff0c;并且可以处理负…

[YM]课设-C#-WebApi-Vue-员工管理系统 (五)登录

分析&#xff1a; 请求路径&#xff1a;/login 请求方式&#xff1a;POST 接口描述&#xff1a;该接口用于员工登录Tlias智能学习辅助系统&#xff0c;登录完毕后&#xff0c;系统下发JWT令牌。 > api文档中提到JWT令牌 这个相对来说比较复杂 是用来加密&#xff0c;…

那些生意好的厂家如何找到目标客户呢?

寻找并精准定位目标客户是任何一家追求持续发展与业务增长的厂家必须掌握的关键技能。那些生意兴隆的厂家之所以能够脱颖而出&#xff0c;很大程度上得益于他们高效且精准的客户寻找策略。今天&#xff0c;我们将深入探讨这些成功厂家如何精准找到并吸引目标客户。 01明确目标…

基于梯度提升系列算法对二手车价格预测分析与研究

目录 1 引言 1.1 研究背景 1.2 研究目的 1.3 研究意义 1.3 国内外现状 1.4 研究思路与组织框架 2 关键技术理论介绍 2.1 二手车市场介绍 2.2 梯度提升回归系列算法介绍 3 数据来源及预处理 3.1 数据来源及说明 3.2 数据预处理及特征变换 第4章 数据分析及可视化 4.1 分析思路及…

自闭症孩子的康复治疗方法

在星贝育园&#xff0c;我们深知自闭症给孩子和家庭带来的巨大挑战。作为特教老师和生活老师&#xff0c;我们秉持着专业、负责的态度&#xff0c;为自闭症患儿提供全方位的康复治疗。 我们实行 24 小时陪伴&#xff0c;365 天全年无休的密集干预模式。这种模式能够确保孩子在任…

[Leetcode 216][Medium]组合总和 III--回溯

目录 一、题目描述 二、整体思路 三、代码 一、题目描述 原题地址 二、整体思路 对于组合问题&#xff0c;首先要想到回溯法。那么可以根据回溯法模版进行设计。 void backtrace(元素){if(满足题目要求的条件){保存目前路径/状态/结果;return;}for循环,往目前状态相邻的所…

100天带你精通Python——第8天面向对象编程

文章目录 前言面向对象技术简介类&#xff08;Class&#xff09;对象&#xff08;Object&#xff09;继承&#xff08;Inheritance&#xff09;封装&#xff08;Encapsulation&#xff09;多态&#xff08;Polymorphism&#xff09;Python类详解静态变量&#xff08;Static Var…

【算法】演员~评论家方法

一、引言 演员-评论家算法&#xff08;Actors-Critics Method&#xff09;是一种用于并发编程中的同步机制&#xff0c;用于解决多线程环境下的资源竞争问题。与传统的锁和信号量等同步工具不同&#xff0c;演员-评论家方法采用更加灵活的协作策略。算法结合了策略梯度&#xf…