Project

General

Profile

Feature #7968 ยป lazyMenu.cpp

Example app - Roel Standaert, 01/11/2021 02:38 PM

 
1
#include <Wt/WApplication.h>
2
#include <Wt/WContainerWidget.h>
3
#include <Wt/WMenu.h>
4
#include <Wt/WStackedWidget.h>
5
#include <Wt/WText.h>
6
#include <Wt/WTextEdit.h>
7

    
8
#include <functional>
9
#include <memory>
10

    
11
class DeferredWidget final : public Wt::WContainerWidget {
12
public:
13
  using WidgetCreator = std::function<std::unique_ptr<Wt::WWidget>()>;
14

    
15
  explicit DeferredWidget(WidgetCreator f);
16
  ~DeferredWidget() override;
17

    
18
  void load() override;
19

    
20
private:
21
  WidgetCreator f_;
22
};
23

    
24
DeferredWidget::DeferredWidget(WidgetCreator f)
25
  : f_(std::move(f))
26
{ }
27

    
28
DeferredWidget::~DeferredWidget() = default;
29

    
30
void DeferredWidget::load()
31
{
32
  if (!loaded()) {
33
    addWidget(f_());
34
  }
35

    
36
  WContainerWidget::load();
37
}
38

    
39
class Application final : public Wt::WApplication
40
{
41
public:
42
  explicit Application(const Wt::WEnvironment &env);
43
  ~Application() override;
44
};
45

    
46
Application::Application(const Wt::WEnvironment &env)
47
  : Wt::WApplication(env)
48
{
49
  auto stack = root()->addNew<Wt::WStackedWidget>();
50
  auto menu = root()->insertNew<Wt::WMenu>(0, stack);
51

    
52
  menu->addItem(Wt::utf8("One"), std::make_unique<DeferredWidget>([]{
53
    return std::make_unique<Wt::WText>(Wt::utf8("One"));
54
  }));
55
  menu->addItem(Wt::utf8("Two"), std::make_unique<DeferredWidget>([]{
56
    return std::make_unique<Wt::WText>(Wt::utf8("Two"));
57
  }));
58
  menu->addItem(Wt::utf8("WTextEdit"), std::make_unique<DeferredWidget>([]{
59
    auto container = std::make_unique<Wt::WContainerWidget>();
60
    auto textEdit = container->addNew<Wt::WTextEdit>();
61
    textEdit->resize(400, 300);
62
    return container;
63
  }));
64
}
65

    
66
Application::~Application() = default;
67

    
68
int main(int argc, char *argv[])
69
{
70
  return Wt::WRun(argc, argv, [](const Wt::WEnvironment &env) {
71
    return std::make_unique<Application>(env);
72
  });
73
}
    (1-1/1)