The first thing to do is to create your combo box. If you try to do the simple
zero argument constructor, you're going to get a box with zero choices, a blank
dropdown. This is what happens when you use the QStandardItemModel
, which
is empty by default. You can choose either to use the QStandardItemModel
or create your own subclass of QAbstractItemModel
.
QComboBox* comboBox = new QComboBox;
Remember that a combo box represents a choice between several items of a list.
So you need some way to specify that list. You have a choice of abstraction
levels here. The simplest way is to use the QStandardItemModel directly, via
the convenience methods provided by QComboBox
. In order of complexity your
other options are.
- Use QStringListModel directly
- Subclass QStringListModel
- Subclass QAbstractListModel
- Subclass QAbstractItemModel
Using QStringModel directly is simple.
QStringList list = {"foo", "bar", "baz"};
QAbstractItemModel* myModel = new QStringListModel(list, comboBox);
comboBox->setModel(myModel);
What if we want to set the selected item?
comboBox->setCurrentIndex(1);
This will set the box to select bar
, given the model above. That is, indices
are zero-based.