Skip to main content

Switch

A compact two state control with a moving thumb and reduced motion support.

Loading preview…
#include <QApplication>
#include <QFile>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QStandardItemModel>
#include <QUrl>
#include <QVBoxLayout>
#include <array>
#ifdef SHADCN_GALLERY_MEDIA
#include <shadcn/media.hpp>
#endif
#include <shadcn/shadcn.hpp>

QWidget* example(QWidget* parent = nullptr) {
using namespace shadcn;
auto* canvas = new QWidget(parent);
canvas->setAutoFillBackground(true);
auto* outer = new QHBoxLayout(canvas);
outer->setContentsMargins(32, 32, 32, 32);
auto* host = new QWidget(canvas);
auto* layout = new QVBoxLayout(host);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(16);
outer->addStretch();
outer->addWidget(host, 0, Qt::AlignCenter);
outer->addStretch();
auto* row = new QHBoxLayout;
row->setSpacing(8);
auto* control = new Switch(host);
auto* label = new Label("Airplane mode", host);
label->setBuddy(control);
row->addWidget(control);
row->addWidget(label);
layout->addLayout(row);
return canvas;
}

Installation​

add_subdirectory(shadcn-cpp)
target_link_libraries(app PRIVATE shadcn::widgets)

Usage​

#include <shadcn/widgets.hpp>

shadcn::Switch autoplay(parent);
autoplay.setAccessibleName("Auto play");
autoplay.setSwitchSize(shadcn::SwitchSize::Sm);
autoplay.setChecked(true);
QObject::connect(&autoplay, &QCheckBox::toggled, receiver, onToggled);

API​

setSwitchSize selects the default or small track. The inherited checked state and toggle signals remain available.

Keyboard and accessibility​

Space toggles the switch. Set an accessible name or connect a visible Label before showing it.