如何在Rust的egui框架中实现内容滚动功能
如何在Rust的egui框架中实现内容滚动功能
嗨,看起来你遇到了egui里内容超出窗口后没法滚动的问题,这很常见,只需要给你的内容套一个滚动容器就搞定啦!
你现在是把所有内容直接放在CentralPanel里,当内容高度超过窗口高度时,超出的部分就会被截断。egui提供了ScrollArea组件,专门用来处理这种需要滚动的长内容场景。
只需要把你CentralPanel里的所有内容,放到ScrollArea::vertical().show(ui, |ui| { ... })这个闭包里面就行。我帮你修改了你的代码,你可以直接参考:
fn main() { let nativeoption = eframe::NativeOptions{/* 你的窗口配置 */}; eframe::run_native( "Portfolio", nativeoption, Box::new(|cc| Box::new(MyEguiApp::new(cc))), ).expect("Failed to run application"); } #[derive(Default)] struct MyEguiApp {} impl MyEguiApp { fn new(_cc: &eframe::CreationContext<'_>) -> Self { Self::default() } fn open_url(&self, url: &str) { if let Err(err) = webbrowser::open(url) { eprintln!("failed to open link {:?} ", err); } } } impl eframe::App for MyEguiApp { fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { egui::CentralPanel::default().show(ctx,|ui| { // 新增:用垂直滚动区域包裹所有内容 egui::ScrollArea::vertical().show(ui, |ui| { if ui.interact(ui.max_rect(), egui::Id::new("window-drag"), egui::Sense::drag()).dragged() { frame.drag_window(); } ui.heading("Hi! I am pretham Muthappa"); ui.separator(); ui.horizontal(|ui| { let _= ui.button("HOME"); if ui.button("ABOUT").clicked() { self.open_url("https://tidersky.me"); } if ui.button("RESUME").clicked() { self.open_url("https://drive.google.com/file/d/1jgWFzMDIrpW9odLQMoljTGtEeofRvf6W/view"); } if ui.button("CONTACT").clicked() { self.open_url("https://tidersky.me") } }); ui.separator(); ui.heading("About"); ui.label("Hello I am pretham muthappa , I am a final year computer science student. I like coding and creating open source projects and apart from coding i do pixel art illstration"); ui.separator(); ui.heading("project"); egui::CollapsingHeader::new("SnapCrawler") .show(ui,|ui| { ui.label("Snapercrawler is a webscrapper tool built using Nodejs and puppeteer , it can scrape any images from most of the website and save it in a directory") }); egui::CollapsingHeader::new("Event-Hive") .show(ui,|ui| { ui.label("Snapercrawler is a webscrapper tool built using ") }); egui::CollapsingHeader::new("Geek-Notes") .show(ui,|ui| { ui.label("Snapercrawler is a webscrapper tool built using ") }); egui::CollapsingHeader::new("Vulkan-rust") .show(ui,|ui| { ui.label("Snapercrawler is a webscrapper tool built using ") }); }); }); } }
修改说明:
在原来的CentralPanel的show闭包内,我们新增了垂直滚动区域的包裹逻辑,把所有UI元素都移到滚动区域的子闭包里。这样当内容高度超过窗口时,就会自动出现垂直滚动条,你可以拖动滚动条或者用鼠标滚轮来查看全部内容了。
额外小提示:
- 如果需要水平滚动,可以用
ScrollArea::horizontal();如果需要双向滚动,用ScrollArea::both() - 你还可以通过链式方法自定义滚动区域的样式,比如设置唯一ID:
ScrollArea::vertical().id_source("main_scroll"),或者限制最大高度:ScrollArea::vertical().max_height(500.0)等等
备注:内容来源于stack exchange,提问作者user20957580
相关产品推荐
相关产品推荐

