Toggle Group
A group of toggles with single or multiple selection semantics.
#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* group = new ToggleGroup(Qt::Horizontal, host);
group->setMode(ToggleGroupMode::Multiple);
for (const auto* text : {"Bold", "Italic", "Underline"}) {
auto* toggle = new Toggle(text, group);
toggle->setVariant(ToggleVariant::Outline);
group->addToggle(*toggle, text);
}
group->setCheckedValues({"Bold"});
layout->addWidget(group);
return canvas;
}
Installation
- Source
- Installed package
add_subdirectory(shadcn-cpp)
target_link_libraries(app PRIVATE shadcn::widgets)
find_package(shadcn CONFIG REQUIRED)
target_link_libraries(app PRIVATE shadcn::widgets)
Usage
#include <shadcn/controls.hpp>
shadcn::ToggleGroup group(Qt::Horizontal, parent);
auto& daily = shadcn::make_child<shadcn::Toggle>(group, "Daily");
auto& weekly = shadcn::make_child<shadcn::Toggle>(group, "Weekly");
group.addToggle(daily, "daily");
group.addToggle(weekly, "weekly");
group.setCheckedValues({"daily"});
API
setMode selects single or multiple behavior. checkedValues and valuesChanged expose the group state.
setCheckedValues emits one group notification when the final selection changes. Individual toggles retain their own signals. In single selection mode, the last matching toggle in the group is selected.
Variations
Use ToggleGroupMode::Multiple for independent filters and set orientation for a stacked group.
Keyboard and accessibility
Tab enters or leaves the group. Arrow keys move focus along its orientation and wrap at either end, skipping disabled and hidden toggles. Horizontal arrows follow the layout direction. Home and End focus the first and last available toggles. Moving focus preserves selection; Space activates the focused toggle.
Qt supplies native focus, keyboard interaction and accessible object roles. Give the component a visible label or an accessible name when its text alone does not explain the action.
Ownership
removeToggle detaches and hides the toggle. It disconnects the group's callbacks while preserving application connections. You can then add the toggle to another group or delete it.
The parent widget owns the component. Child widgets created through a component layout follow Qt parent ownership. References returned by helper methods are borrowed.