egui icon indicating copy to clipboard operation
egui copied to clipboard

Support Negative `desired_width` in TextEdit

Open varphone opened this issue 1 month ago • 2 comments

Support Negative desired_width in TextEdit

Summary

This PR adds support for negative values in TextEdit::desired_width(), allowing developers to specify width relative to available space by subtraction.

Changes

  • Core Feature: Modified TextEdit::desired_width() to accept negative values

    • Negative values subtract from available width (e.g., -50.0 means available_width - 50.0)
    • Maintains backward compatibility with existing positive values and f32::INFINITY
    • Added documentation explaining the new behavior
  • Demo: Added example showcasing the feature

    • Demonstrates a singleline TextEdit that reserves space for a Clear button
    • Made the demo window resizable to show dynamic behavior
    • Added hover tooltip for better user understanding

Use Case

This is particularly useful when you want a TextEdit to fill most of the available space while leaving room for adjacent widgets (like buttons) in the same horizontal layout:

ui.horizontal(|ui| {
    ui.add(egui::TextEdit::singleline(&mut text).desired_width(-50.0));
    if ui.button("Clear").clicked() {
        text.clear();
    }
});

Implementation Details

  • Width calculation now handles three cases:
    1. f32::INFINITY: uses full available width
    2. Positive values: uses minimum of desired and available width
    3. Negative values: subtracts from available width with a minimum of 0.0

Testing

  • Tested with the demo application
  • Verified behavior when resizing the window
  • Confirmed backward compatibility with existing code

varphone avatar Nov 15 '25 05:11 varphone

Preview available at https://egui-pr-preview.github.io/pr/7717-featuretextedit-negative-desiredwidth Note that it might take a couple seconds for the update to show up after the preview_build workflow has completed.

View snapshot changes at kitdiff

github-actions[bot] avatar Nov 15 '25 05:11 github-actions[bot]

This feels like a unique snowflake. Why would negative values work that way for TextEdit, and nothing else?

And why can't the user just call .desired_width(ui.available_width() - 50.0) instead?

emilk avatar Nov 25 '25 07:11 emilk