Widget trait.
The Widget Trait
TheWidget trait is the core abstraction for creating interactive components:
Simple Custom Widget Example
Here’s a complete example of a simple circle widget:Using Your Custom Widget
Widget Trait Methods
Required Methods
size
Returns the size constraints of the widget:layout
Computes the layout of the widget:draw
Renders the widget:Optional Methods
update
Handles events:mouse_interaction
Returns the mouse cursor interaction:Stateful Widgets
For widgets that need state, use thetag and state methods:
Widgets with Children
For container-like widgets:Advanced: Canvas Widget
For complex graphics, use thecanvas widget with a Program:
Examples in the Repository
The Iced repository contains several custom widget examples:custom_widget- A simple circle widget demonstrating the basicsgeometry- Using the canvas widget for complex graphicscustom_quad- Low-level quad renderingcustom_shader- Using custom shaders with widgets
Best Practices
Start with canvas for graphics-heavy widgets
Start with canvas for graphics-heavy widgets
If your widget primarily involves custom graphics, use the
canvas widget with a Program instead of implementing Widget directly. It’s simpler and more efficient.Minimize state
Minimize state
Keep widget state minimal. Prefer deriving visual state from the view function’s parameters rather than storing it in widget state.
Use intrinsic sizing
Use intrinsic sizing
Provide sensible intrinsic sizes in the
layout method so your widget works well with Length::Shrink.Handle all event types
Handle all event types
In the
update method, handle or explicitly ignore all relevant event types to avoid surprising behavior.Provide builder methods
Provide builder methods
Add convenient builder methods for common configurations:
Next Steps
Layout
Understand layout computation
Styling
Learn about widget styling
