How to scroll to a particular button from outside the scrollarea? #4698
-
I have this let row_height = ui.spacing().interact_size.y;
let total_rows = &self.dir_list.len();
egui::ScrollArea::vertical().min_scrolled_height(428.0).show_rows(ui, row_height, *total_rows, |ui, row_range| {
for row in row_range {
let element = &self.dir_list[row];
if *element == self.selected {
let (r, g, b) = (self.settings_rgb.colour3[0], self.settings_rgb.colour3[1], self.settings_rgb.colour3[2]);
if ui.add(egui::Button::new(element).fill(egui::Color32::from_rgb(r, g, b))).clicked() {}
} else {
let (r, g, b) = (self.settings_rgb.colour2[0], self.settings_rgb.colour2[1], self.settings_rgb.colour2[2]);
if ui.add(egui::Button::new(element).fill(Color32::from_rgb(r, g, b))).clicked() {
self.selected = element.to_string();
self.regenerate_list_selected = element.to_string()
}
}
}
}); I want to make a button outside of it that will scroll to a particular row. For example, click button scroll to row 200, etc. Is that possible? Something like this: if ui.button("Scroll to ID 600").clicked() {
// Scroll to 600 code here
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There is the method Response::scroll_to_me that does that. However, when using egui::CentralPanel::default().show(ctx, |ui| {
let total_rows = 10_000;
let text_style = egui::TextStyle::Body;
let row_height = ui.text_style_height(&text_style);
let spacing = ui.spacing().item_spacing.y;
// let row_height = ui.spacing().interact_size.y; // if you are adding buttons instead of labels.
let response = ui.add(egui::Slider::new(&mut self.scroll_to, 0..=total_rows));
let scroll_to = response.changed().then_some(self.scroll_to);
let mut scroll_area = ScrollArea::vertical();
if let Some(item) = scroll_to {
scroll_area = scroll_area.vertical_scroll_offset(
row_height * item as f32 + spacing * (item.saturating_sub(1) as f32),
);
}
scroll_area.show_rows(ui, row_height, total_rows, |ui, row_range| {
for row in row_range {
let text = format!("Row {}/{}", row + 1, total_rows);
let response = ui.label(text);
if scroll_to == Some(row) {
response.scroll_to_me(Some(egui::Align::Center));
}
}
});
}); Screencast.from.2024-06-24.19-24-09.mp4 |
Beta Was this translation helpful? Give feedback.
There is the method Response::scroll_to_me that does that. However, when using
show_rows
instead ofshow
, the rows out of view are not run at all, so you first need to bring the row you want into view usingvertical_scroll_offset
, so its response gets created and you can scroll to it, although technically you only need thescroll_to_me
part after that if you want to use theAlign
to get the row where you want (top, center etc). Here's an example: