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

news2024/9/21 2:36:08

前言
本专栏是关于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/2082324.html

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

相关文章

Ubuntu 24.04 安装 intel 编译器

目录 1.采用用户界面 GUI 安装英特尔基本工具包 Intel oneAPI Base Toolkit 1.1 下载离线英特尔基本工具包 1.2 安装英特尔基本工具包 1.3 英特尔基本工具包 Intel oneAPI Base Toolkit 环境设置 2.安装英特尔基本工具包 Intel HPC Toolkit 2.1 下载离线英特尔高性能计算…

智能座舱高通8155摄像头方案

高通汽车开发平台 &#xff08;ADP&#xff09;基于8155的多媒体硬件框图如下所示&#xff1a;有4个4路CSI摄像头处理通路&#xff0c;2个4路DSI屏幕处理通路&#xff0c;1个DisplayPort。 基于摄像头的详细方案如下&#xff1a;可以处理4路MAX9296解串后信号。 再深入细化基于…

Java10 集合

集合 集合集合接口等级&#xff1a;Collection&#xff1a;单例集合接口,将数据一个一个存储&#xff0c;存储的是值。ArrayList类&#xff1a;泛型集合Linkedlist集合&#xff1a;Vector集合&#xff1a;Stack集合&#xff1a;Vetor的子类 Set接口&#xff1a;存储是无序的&am…

【使用 Python 进行截图的两种方法】

在 Python 中&#xff0c;可以使用 pyautogui 和 Pillow 进行截图 使用 pyautogui 进行截图时&#xff0c;其提供了方便的函数。例如&#xff0c;使用 pyautogui.screenshot() 函数可以获取整个屏幕的截图&#xff0c;该函数返回一个包含屏幕截图的图像对象。如果不想截取整个…

最大噪音值甚至受法规限制,如何基于LBM算法有效控制风扇气动噪音

风扇的气动噪声 在工业设备行业&#xff0c;最大噪音值受法规限制。在很多使用风扇冷却的设备上&#xff0c;风扇噪声通常是这些设备工作噪声的最大贡献量。而在家电民用行业&#xff0c;例如空调、空气净化器、油烟机等&#xff0c;其噪音大小直接关系到用户的体验感受&#x…

从零开始掌握容器技术:Docker的奇妙世界

容器技术在当今的云计算和软件开发领域中扮演着越来越重要的角色。如果你是一名计算机专业的学生或从事IT行业的从业者&#xff0c;可能已经听说过Docker这个词。它在软件开发、部署、运维等环节中大放异彩&#xff0c;但对于刚接触这个概念的朋友来说&#xff0c;可能还是有些…

【乐企】有关乐企能力测试接口对接(详细)

1、申请密钥 2、验证本地服务器与乐企服务器的连通性 乐企服务器生产和测试域名均为&#xff1a;https://lqpt.chinatax.gov.cn:8443。开发者可以在“能力中心”查看基础公用能力详情&#xff0c;按照能力接入和开发指引完成接口对接&#xff0c;验证服务器连通性和证书配置正确…

给一个web网站,如何开展测试?

前言 Web测试是指针对Web应用程序(网站或基于Web的系统)进行的测试活动&#xff0c;以确保其质量、性能、安全性、可用性和兼容性等方面符合预期标准。Web测试涵盖了从前端用户界面(UI)到后端逻辑和数据库的各个方面&#xff0c;确保Web应用程序在不同环境和条件下都能正常运行…

参会投稿 | 第三届先进传感与智能制造国际学术会议(ASIM 2024)

第三届先进传感与智能制造国际会议&#xff08;The 3rd International Conference on Advanced Sensing, Intelligent Manufacturing&#xff09;&#xff0c;由江汉大学、西安交通大学和山东大学主办&#xff0c;由江西省机械工程学会、东华理工大学机械与电子工程学院等联合协…

Hibernate 批量插入速度慢的原因和解决方法

由于业务需要一次性连续写入超过10k条以上的新数据&#xff0c;当对象超过10个成员变量以后&#xff0c;整个写入过程居然需要长达35秒&#xff0c;这个速度是不能接受的&#xff0c;故此研究了一下怎么开启Hibernate批量写入的功能。 我这边使用的是Hibernate 5.6.15 在网上…

推动光模块技术发展:从400G、800G到1.6T

随着数据通信领域的持续发展&#xff0c;对于更快、更高传输速率的需求也在不断增长。作为现代数据传输的基石&#xff0c;光模块技术不断进步以满足这一需求。其中一项重大进展是网络速率从400G提升到800G&#xff0c;并将向1.6T继续发展。让我们深入探讨这些技术的演变&#…

Java语言程序设计基础篇_编程练习题***17.9 (地址簿)

目录 题目&#xff1a;***17.9 (地址簿) 习题思路 代码示例 结果展示 题目&#xff1a;***17.9 (地址簿) 编写程序用于存储、返回、增加&#xff0c;以及更新如图 17-20 所示的地址薄。使用固定长度的字符串来存储地址中的每个属性。使用随机访问文件来读取和写人一个地址…

刚刚认证!网络主播成为国家新职业,易播易赚打造打造职业入门全新模式

近期&#xff0c;人力资源和社会保障部会同国家市场监督管理总局、国家统计局日前增设网络主播为国家新职业&#xff0c;这标志着网络主播的职业身份在“国家确定职业分类”上首次得以确立。 据人社部此前印发的《关于加强新职业培训工作的通知》表示&#xff0c;新职业从业者可…

代码随想录算法训练营第二十三天| 39. 组合总和 40.组合总和II 131.分割回文串

目录 一、LeetCode 39. 组合总和思路&#xff1a;C代码 二、LeetCode 40.组合总和II思路C代码 三、LeetCode 131.分割回文串思路C代码 总结 一、LeetCode 39. 组合总和 题目链接&#xff1a;LeetCode 39. 组合总和 文章讲解&#xff1a;代码随想录 视频讲解&#xff1a;带你学…

直播平台直播API集成之快手篇

前言: 本篇我们来介绍如何使用快手 的直播API创建直播。 准备工作: 1、你首先得有个快手账号; 2、创建快手应用,填写应用审核信息,等待应用创建审核通过,应用成功创建后在开发与上线前还要提前做好API权限申请,如果你只需要获取用户基本信息,以及得到直播API的访问权限…

Python | Leetcode Python题解之第377题组合总和IV

题目&#xff1a; 题解&#xff1a; class Solution:def combinationSum4(self, nums: List[int], target: int) -> int:dp [1] [0] * targetfor i in range(1, target 1):for num in nums:if num < i:dp[i] dp[i - num]return dp[target]

合宙LuatOS产品规格书——Air700EMQ

Air700EMQ是合宙通信的LTE Cat.1bis通信模块&#xff0c; 依托移芯EC716E平台&#xff0c;支持先进的LTE 3GPP Rel.13技术。 主要特点如下&#xff1a; 1. 技术平台与标准支持&#xff1a; Air700EMQ采用移芯EC716E平台&#xff0c;基于先进的LTE技术。支持LTE 3GPP Releas…

leetcode234. 回文链表(java实现)

题目描述&#xff1a; 本道题的思路可以使用集合先存储链表的值&#xff0c;然后进行判断即可。 总体思路比较简单。 代码实现&#xff1a; class Solution {public boolean isPalindrome(ListNode head) {List<Integer> res new ArrayList();ListNode cur head;whil…

3分钟快速本地搭建RSShub服务器并结合内网穿透实现无公网IP远程访问

文章目录 前言1. Docker 安装2. Docker 部署Rsshub3. 本地访问Rsshub4. Linux安装Cpolar5. 配置公网地址6. 远程访问Rsshub7. 固定Cpolar公网地址8. 固定地址访问 前言 今天和大家分享的是如何在本地快速简单部署Rsshub工具&#xff0c;并结合cpolar内网穿透工具使用公网地址远…

Remote Sensing(MDPI)期刊投稿历程(CV方向)

一、期刊简介 期刊官网&#xff1a;https://www.mdpi.com/journal/remotesensing 影响因子&#xff08;2024&#xff09;&#xff1a;4.2 分区&#xff1a;JCR:Q1。中科院二区 版面费&#xff1a;2700瑞士法郎&#xff08;约21000rmb&#xff09; 二、投稿时间线 2024.06.20…