Skip to main content

Field

A label, description, control and validation message in one layout.

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* field = new Field("Email", host);
field->setFixedWidth(340);
auto* input = new Input(field);
input->setPlaceholderText("you@example.com");
field->setControl(input);
field->setDescription("We will use this address to contact you.");
layout->addWidget(field);
return canvas;
}

Installation​

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

Usage​

#include <shadcn/data.hpp>

shadcn::Field field("Email", parent);
auto& input = shadcn::make_child<shadcn::Input>(field);
field.setControl(&input);
field.setDescription("We use this for account notices.");
field.setValidator([&] {
return input.text().contains('@')
? QString{} : QString{"Enter a valid email."};
});
field.validate();

API​

setControl makes the field the control's Qt parent. Replacing the control detaches the old widget without deleting it. The caller then owns the detached widget. setValidator returns an error string from application validation.

Variations​

Use setError for server feedback and setDescription for guidance before validation.

Keyboard and accessibility​

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​

The parent widget owns the component. Child widgets created through a component layout follow Qt parent ownership. References returned by helper methods are borrowed.