Search code examples
user-interfacerusteguieframe

Add widget at screen space position egui


I'm relatively new to egui and I have a project using it and eframe where I'd like a few labels floating within a layout (i.e. not locked to a grid, and able to be dragged to different locations with the mouse) and I have most of the functionality established but I don't know how to set the location of a widget to a screen space position. I haven't found any documentation that describes how to do this and .with_new_rect() has no noticeable effect. Putting the labels within a layout and using ui.add_space() could work but since spacing only works along a single axis it would be too limiting.


Solution

  • The docs of Ui::label note:

    Shortcut for add(Label::new(text))

    That is, ui.label("foobar") is ui.add(Label::new("foobar")). The docs of Ui:add note:

    See also Self::add_sized and Self::put.

    The latter says:

    Add a Widget to this Ui at a specific location (manual layout).

    So, to place a label at a particular position x, y with size w, h:

    ui.put(egui::Rect::from_min_max(
        egui::pos2(x, y),
        egui::vec2(w, h),
    ), egui::Label::new("foobar"));
    

    Note that you say "screen space" position, but this is still relative to the window. I assume that's what you meant; otherwise you would additionally have to offset the position by the window's current position.