Aspect Ratio
A layout wrapper that keeps one child at a fixed width to height ratio.
Loading preview…
Live C++Source and licences
#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* aspect = new AspectRatio(16.0 / 9.0, host);
aspect->setFixedWidth(320);
auto* label = new QLabel("16 : 9", aspect);
label->setAlignment(Qt::AlignCenter);
label->setAutoFillBackground(true);
auto palette = label->palette();
palette.setColor(QPalette::Window, palette.color(QPalette::AlternateBase));
label->setPalette(palette);
aspect->setWidget(*label);
layout->addWidget(aspect);
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>
#include <QLabel>
shadcn::AspectRatio frame(16.0 / 9.0, parent);
auto* preview = new QLabel("Preview", &frame);
frame.setWidget(*preview);
API
setRatio changes the ratio. setWidget installs the single child and heightForWidth lets Qt negotiate the size.
Variations
Use a square ratio for avatars or a wide ratio for media previews.
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.