Skip to main content

Radio Group

A vertical group of mutually exclusive native radio buttons.

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* group = new RadioGroup(host);
for (const auto* text : {"Default", "Comfortable", "Compact"})
group->addItem(*new RadioGroupItem(text, group), text);
group->setCheckedValue("Comfortable");
layout->addWidget(group);
return canvas;
}

Installation​

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

Usage​

#include <shadcn/controls.hpp>

shadcn::RadioGroup group(parent);
auto& email = shadcn::make_child<shadcn::RadioGroupItem>(
group, "Email");
group.addItem(email, "email");
group.setCheckedValue("email");

API​

addItem binds a value to each radio item. checkedValue reads the selected value and valueChanged reports changes.

setCheckedValue selects a matching item. An unmatched value clears the selection and reports an empty value. Clearing an already empty group emits nothing.

Variations​

Add descriptions beside a radio item when the choice needs more context.

Keyboard and accessibility​

Tab enters at the selected option and then leaves the group. Arrow keys move focus and selection together, wrap at either end and skip disabled or hidden options. Left and Right follow the layout direction. Control, Alt and Meta arrow shortcuts leave the selection unchanged.

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​

removeItem detaches and hides the radio item. It disconnects the group's callbacks while preserving application connections. You can then add the item 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.