I will document some design patterns I’ve used while writing complicated GUIs in Rust with egui. This is not an introduction to Rust or Egui.
Multiple Panels
This example shows how to make a UI that can switch between multiple panels/states/UIs/whatever you want to call them. This is accomplished by having a struct, StateUi
, which holds any state and can be instructed to switch states with the Action
enum. Note that this does not preserve State when switching between the UIs.
|
|
Any number of additional UIs can be added, as long as they implement the State
trait
Multiple Panels Preserving State
This example is similar to the one above, but each UI is preserved when switching. The major difference is that the panels are held in a vector but only one is shown at a time, determined by state_idx
.
|
|
Running Complex Operations
This example shows how a button can invoke a complex operation that may take a while without blocking the main thread. Note how we call request_repaint_after
if the task is not yet done. Without this, the UI would only update on mouse movement and the user would wait and wait an wait.
While this method feels ugly, it keeps the complexity spirit demon at bay by keeping everything within the JoinHandle
, rather than having separate start_task()
, is_finished()
, and get_result()
functions. However, I’ll admit that having an Option<JoinHandle<Result<Vec<Users>, FetchError>>>
in your UI doesn’t look nice.
|
|
This relies on the glorious take() method which I encourage you to learn about