Project

General

Profile

RE: Change bootstrap3 theme on the fly ยป forum_16948.cpp

Roel Standaert, 04/16/2020 03:40 PM

 
#include <Wt/WApplication.h>
#include <Wt/WBootstrapTheme.h>
#include <Wt/WContainerWidget.h>
#include <Wt/WLinkedCssStyleSheet.h>
#include <Wt/WPushButton.h>

#include <cassert>
#include <memory>
#include <vector>

class BootstrapTheme final : public Wt::WBootstrapTheme {
public:
BootstrapTheme();
~BootstrapTheme() override;
std::vector<Wt::WLinkedCssStyleSheet> styleSheets() const override;
};

BootstrapTheme::BootstrapTheme()
{
setVersion(Wt::BootstrapVersion::v3);
}

BootstrapTheme::~BootstrapTheme()
{ }

std::vector<Wt::WLinkedCssStyleSheet> BootstrapTheme::styleSheets() const
{
auto result = WBootstrapTheme::styleSheets();
while (result.size() > 1) {
result.erase(result.begin());
}
return result;
}

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

private:
enum class Theme {
Darkly,
Flatly
};

Theme currentTheme_;
};

Application::Application(const Wt::WEnvironment & env)
: Wt::WApplication(env),
currentTheme_(Theme::Darkly)
{
setTheme(std::make_shared<BootstrapTheme>());
useStyleSheet("/darkly/bootstrap.min.css");

auto container = root()->addNew<Wt::WContainerWidget>();
container->addStyleClass("container");

auto row = container->addNew<Wt::WContainerWidget>();
row->addStyleClass("row");

auto col = row->addNew<Wt::WContainerWidget>();
col->addStyleClass("col-md-3");

auto switchStylesheetsButton = col->addNew<Wt::WPushButton>(Wt::utf8("Switch stylesheets"));
switchStylesheetsButton->addStyleClass("btn-primary");
switchStylesheetsButton->clicked().connect([this]{
if (currentTheme_ == Theme::Darkly) {
removeStyleSheet("/darkly/bootstrap.min.css");
currentTheme_ = Theme::Flatly;
useStyleSheet("/flatly/bootstrap.min.css");
} else if (currentTheme_ == Theme::Flatly) {
removeStyleSheet("/flatly/bootstrap.min.css");
currentTheme_ = Theme::Darkly;
useStyleSheet("/darkly/bootstrap.min.css");
} else {
assert(false);
}
});
}

Application::~Application()
{ }

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