Help with alignment in eframe/egui

The following trivial problem nearly drove me crazy and occupied me for hours: I'm using eFrame and eGUI to design a GUI. Various buttons, etc., are supposed to be arranged in a row at the top of the window. However, the second requirement is causing a problem: this row should be horizontally centered. In HTML, I would put everything in a row in a div and center the div, but that just doesn't work. I've tried numerous times, but nothing has really worked. Either the objects (labels for testing purposes) aren't in a row or they aren't horizontally centered at the top.

So the following code is not working (just one example):

fn update(&mut self, ctx: &eframe::egui::Context, _frame: &mut eframe::Frame) {

        egui::CentralPanel::default().show(ctx, |ui| {

           ui.with_layout(
              egui::Layout::top_down(egui::Align::Center),
              |ui| {
                  ui.horizontal(|ui| {
                      ui.label("Test1");
                      ui.label("Test2");
                      ui.label("Test3");
                  });
               },
            );
                   
            
        });
    }

Please help!

It is rather hard with an immediate-mode GUI: once you are creating the widget, you have to place it on canvas already, you cannot wait for other widgets of this frame (you can use previous frame's info though) to be placed.

However you can create a block with all these labels, specify its total width and center that.

1 Like

this is the kind of case that a single pass layout algorithm is incapable of doing.

common "solutions" includes:

  • used fixed width to the inner labels;
  • pre-calculate/pre-measure the width of the labels, and them render them at calculated position
  • multi-pass rendering, i.e. use separate pass for sizing and rendering

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.