A selection box shows an immediately visible list allowing you to choose one (by default) or more options.
A WSelectionBox corresponds to an HTML <select>
element.
WSelectionBox
is a View widget (see also
Model-View-Controller).
By default a WStringListModel is used. With this model you can associate a
single column of data to the displayed items. The member
methods addItem()
, insertItem()
and
removeItem()
manipulate the model. You can set the model
with setModel()
. See the Combo box section for an example.
A model supports different roles like
Wt::ItemDataRole::DisplayRole
and
Wt::ItemDataRole::UserRole
. The suggestion text for an
item in the drop-down box is associated with a
Wt::ItemDataRole::DisplayRole
. The value, which will be
inserted in the line-edit, corresponding with a suggestion, is
stored as Wt::ItemDataRole::UserRole
) data. If no
UserRole data is available, the behaviour defaults to inserting
the suggestion text itself.
If you want to associate multiple data columns with an item from the combo box then you should assign another model to this control like WStandardItemModel or an implementation of WAbstractTableModel.
Note that there are still other models like WFormModel which and can be used to represent fields in a form.
Use shift and/or ctrl-click to select your pizza toppings...
#include <Wt/WContainerWidget.h>
#include <Wt/WSelectionBox.h>
#include <Wt/WText.h>
auto container = std::make_unique<Wt::WContainerWidget>();
Wt::WSelectionBox *sb2 = container->addNew<Wt::WSelectionBox>();
sb2->addItem("Bacon");
sb2->addItem("Cheese");
sb2->addItem("Mushrooms");
sb2->addItem("Green peppers");
sb2->addItem("Ham");
sb2->addItem("Pepperoni");
sb2->addItem("Red peppers");
sb2->addItem("Turkey");
sb2->setSelectionMode(Wt::SelectionMode::Extended);
std::set<int> selection; // By default select the items with index 1 and 4.
selection.insert(1); // Index 1 corresponds to the 2nd item.
selection.insert(4); // Index 4 corresponds to the 5th item.
sb2->setSelectedIndexes(selection);
sb2->setMargin(10, Wt::Side::Right);
Wt::WText *out = container->addNew<Wt::WText>();
out->addStyleClass("help-block");
sb2->activated().connect([=] {
Wt::WString selected;
std::set<int> newSelection = sb2->selectedIndexes();
for (std::set<int>::iterator it = newSelection.begin();
it != newSelection.end(); ++it) {
if (!selected.empty())
selected += ", ";
selected += sb2->itemText(*it);
}
out->setText(Wt::WString("You choose {1}.").arg(selected));
});