Skip to main content

Alert dialog

A confirmation dialog that keeps focus inside the modal until the user chooses an action.

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;
const QString name = "alert-dialog";
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();
Dialog* dialog = name == "alert-dialog" ? static_cast<Dialog*>(new AlertDialog(canvas))
: name == "sheet" ? static_cast<Dialog*>(new Sheet(Side::Right, canvas))
: name == "drawer" ? static_cast<Dialog*>(new Drawer(canvas))
: new Dialog(canvas);
dialog->setTitle(name == "alert-dialog" ? "Are you sure?" : "Edit profile");
dialog->setDescription(name == "alert-dialog"
? "This action cannot be undone."
: "Make changes to your profile here. Save when you are done.");
if (name != "alert-dialog") {
auto* label = new Label("Name", &dialog->panel());
auto* input = new Input(&dialog->panel());
input->setText("Alex Morgan");
label->setBuddy(input);
dialog->content().addWidget(label);
dialog->content().addWidget(input);
auto* save = new Button("Save changes", &dialog->panel());
dialog->footer().addWidget(save);
QObject::connect(save, &Button::clicked, dialog, &Dialog::accept);
}
auto* button = new Button(name == "alert-dialog" ? "Delete account" : "Edit profile", host);
button->setVariant(Variant::Outline);
layout->addWidget(button);
QObject::connect(button, &Button::clicked, dialog, &Dialog::open);
return canvas;
}

Installation​

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

Usage​

#include <shadcn/overlays.hpp>

shadcn::AlertDialog dialog(&window);
dialog.setTitle("Delete account?");
dialog.setDescription("This action cannot be undone.");
QObject::connect(&dialog.actionButton(), &shadcn::Button::clicked,
&dialog, &QDialog::accept);
dialog.open();

Use cancelButton() for the safe action and actionButton() for the destructive action.

API​

The two action buttons are owned by the dialog. Their borrowed references stay valid while the dialog exists.

Keyboard and accessibility​

The dialog keeps focus inside the modal and does not close when the user clicks outside it. Use a clear title and describe the result before the action.