Custom Widget Example
The custom widget example demonstrates how to create a completely custom widget in Iced by implementing theWidget trait. This example builds a simple circle widget with adjustable radius.
Features
- Custom circle widget from scratch
- Implements core
Widgettrait - Custom layout calculation
- Custom rendering
- Interactive slider control
- Demonstrates widget conversion to
Element
Running the Example
The Widget Trait
To create a custom widget, implement theWidget trait:
Circle Widget Implementation
1. Widget Structure
2. Size Specification
3. Layout Calculation
- Limits: Constraints on size (min/max width/height)
- Node: Resulting layout with computed size and position
- Tree: State tree for stateful widgets
4. Drawing
border::rounded(self.radius)) becomes a circle.
Available drawing primitives:
fill_quad: Filled rectangle with bordersfill_text: Text renderingfill_paragraph: Multi-line text- Custom primitives through the renderer
5. Element Conversion
Using the Custom Widget
Advanced Widget Features
Stateful Widgets
For widgets that need internal state:Event Handling
Status::Captured: Event was handled, stop propagationStatus::Ignored: Event was not handled, continue propagation
Mouse Interaction
Idle: Default cursorPointer: Pointing handGrab: Open handGrabbing: Closed handCrosshair: CrosshairText: Text I-beamResizingHorizontally: Horizontal resizeResizingVertically: Vertical resize
Composite Widgets
Widgets can contain other widgets:Canvas Widget
For more complex graphics, use theCanvas widget:
Widget Best Practices
- Keep widgets simple: Each widget should have a single responsibility
- Use composition: Combine simple widgets rather than building complex ones
- Minimize state: Prefer stateless widgets when possible
- Respect layouts: Don’t ignore the limits provided by the layout system
- Handle events properly: Return
Status::Capturedonly when you handle an event - Consider performance: Cache expensive computations in state
- Document clearly: Widget APIs should be clear and well-documented
- Theme-aware: Use theme colors instead of hardcoding
Common Patterns
Theme-Aware Colors
Hover Effects
Related Examples
- Geometry - Mesh2D primitive example
- Custom Quad - Custom quad rendering
- Custom Shader - Custom shader example
- Clock - Canvas-based clock
- Bezier Tool - Complex canvas example
Source Code
View the complete example on GitHub:Next Steps
- Create an interactive widget with click handling
- Build a custom progress indicator
- Implement a color picker widget
- Create an animated widget
- Build a chart/graph widget
- Implement drag-and-drop functionality
- Create a custom text editor widget
- Build a virtual list widget for large datasets
