Project

General

Profile

Feature #7968 ยป lazyMenu.cpp

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

 
#include <Wt/WApplication.h>
#include <Wt/WContainerWidget.h>
#include <Wt/WMenu.h>
#include <Wt/WStackedWidget.h>
#include <Wt/WText.h>
#include <Wt/WTextEdit.h>

#include <functional>
#include <memory>

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

explicit DeferredWidget(WidgetCreator f);
~DeferredWidget() override;

void load() override;

private:
WidgetCreator f_;
};

DeferredWidget::DeferredWidget(WidgetCreator f)
: f_(std::move(f))
{ }

DeferredWidget::~DeferredWidget() = default;

void DeferredWidget::load()
{
if (!loaded()) {
addWidget(f_());
}

WContainerWidget::load();
}

class Application final : public Wt::WApplication
{
public:
explicit Application(const Wt::WEnvironment &env);
~Application() override;
};

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

menu->addItem(Wt::utf8("One"), std::make_unique<DeferredWidget>([]{
return std::make_unique<Wt::WText>(Wt::utf8("One"));
}));
menu->addItem(Wt::utf8("Two"), std::make_unique<DeferredWidget>([]{
return std::make_unique<Wt::WText>(Wt::utf8("Two"));
}));
menu->addItem(Wt::utf8("WTextEdit"), std::make_unique<DeferredWidget>([]{
auto container = std::make_unique<Wt::WContainerWidget>();
auto textEdit = container->addNew<Wt::WTextEdit>();
textEdit->resize(400, 300);
return container;
}));
}

Application::~Application() = default;

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