From cc9a5fc00a1fec0898b7b8268354068a66a6ef12 Mon Sep 17 00:00:00 2001 From: Clark Moody Date: Fri, 2 Feb 2024 10:45:37 -0600 Subject: [PATCH] Update QR code example with theme selector --- examples/qr_code/src/main.rs | 60 ++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/examples/qr_code/src/main.rs b/examples/qr_code/src/main.rs index 867ebfa415..71a30e3665 100644 --- a/examples/qr_code/src/main.rs +++ b/examples/qr_code/src/main.rs @@ -1,6 +1,8 @@ +use iced::color; +use iced::theme::{Palette, Theme}; use iced::widget::qr_code::{self, QRCode}; -use iced::widget::{column, container, text, text_input}; -use iced::{Alignment, Color, Element, Length, Sandbox, Settings}; +use iced::widget::{column, container, radio, row, text, text_input}; +use iced::{Alignment, Element, Length, Sandbox, Settings}; pub fn main() -> iced::Result { QRGenerator::run(Settings::default()) @@ -10,11 +12,20 @@ pub fn main() -> iced::Result { struct QRGenerator { data: String, qr_code: Option, + theme: Theme, +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum ThemeType { + Light, + Dark, + Custom, } #[derive(Debug, Clone)] enum Message { DataChanged(String), + ThemeChanged(ThemeType), } impl Sandbox for QRGenerator { @@ -41,13 +52,30 @@ impl Sandbox for QRGenerator { self.data = data; } + Message::ThemeChanged(theme) => { + self.theme = match theme { + ThemeType::Light => Theme::Light, + ThemeType::Dark => Theme::Dark, + ThemeType::Custom => Theme::custom( + String::from("Custom"), + Palette { + background: color!(0x1d1a05), + text: color!(0xfffbbd), + primary: color!(0xca3c25), + success: color!(0x000000), + danger: color!(0x000000), + }, + ), + }; + if self.qr_code.is_some() { + self.qr_code = qr_code::State::new(&self.data).ok(); + } + } } } fn view(&self) -> Element { - let title = text("QR Code Generator") - .size(70) - .style(Color::from([0.5, 0.5, 0.5])); + let title = text("QR Code Generator").size(70); let input = text_input("Type the data of your QR code here...", &self.data) @@ -55,7 +83,23 @@ impl Sandbox for QRGenerator { .size(30) .padding(15); - let mut content = column![title, input] + let choose_theme = + [ThemeType::Light, ThemeType::Dark, ThemeType::Custom] + .iter() + .fold(row![text("Theme:")].spacing(10), |row, theme| { + row.push(radio( + format!("{theme:?}"), + *theme, + Some(match self.theme { + Theme::Light => ThemeType::Light, + Theme::Dark => ThemeType::Dark, + Theme::Custom { .. } => ThemeType::Custom, + }), + Message::ThemeChanged, + )) + }); + + let mut content = column![title, input, choose_theme] .width(700) .spacing(20) .align_items(Alignment::Center); @@ -72,4 +116,8 @@ impl Sandbox for QRGenerator { .center_y() .into() } + + fn theme(&self) -> Theme { + self.theme.clone() + } }