Skip to main content

Combobox

A searchable select built on the native Qt option model.

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 = "combobox";
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();
NativeSelect* select = name == "combobox" ? static_cast<NativeSelect*>(new Combobox(host))
: name == "select" ? static_cast<NativeSelect*>(new Select(host))
: new NativeSelect(host);
select->setFixedWidth(240);
select->addItems({"Apple", "Banana", "Blueberry", "Grapes", "Pineapple"});
select->setCurrentIndex(-1);
select->setPlaceholderText("Select a fruit");
select->setAccessibleName("Fruit");
if (auto* combo = qobject_cast<Combobox*>(select))
combo->setPlaceholderText("Search fruit...");
layout->addWidget(select);
return canvas;
}

Installation​

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

Usage​

#include <shadcn/data.hpp>

shadcn::Combobox countries(parent);
countries.setPlaceholderText("Find a country");
countries.addItems({"Bangladesh", "Canada", "Japan"});

API​

Combobox inherits Select and QComboBox. Use inherited current index and item data APIs.

Variations​

Add groups or disable an item through the inherited Select helpers.

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.