I'd like to be able to access the values in my QComboBox without having to loop over the contents using itemText.
for( auto i = 0u; i < myQComboBox->count(); i++ )
{
result[i] = myQComboBox->itemText( i );
}
Is there a way that I can get to QComboBox's underlying QList so I can just use the operator[] or even better, iterators and range based loops?
It appears that you're hung on the syntax: you want to replace myQComboBox->itemText(i) with myQComboBox[i]. That can be rather easily done:
// implementation
class ModelAdapter {
QPointer<QAbstractItemModel> m_model;
public:
explicit ModelAdapter(QComboBox & box) : m_model(box.model()) {}
explicit ModelAdapter(QAbstractItemModel * model) : m_model(model) {}
QVariant operator[](int i) { return m_model->index(i, 0); }
};
// point of use
ModelAdapter model(myQComboBox);
for( auto i = 0; i < myQComboBox->count(); i++ )
{
result[i] = model[i];
}
With a good compiler, you can do the below and have it produce the same code as if you used combobox.model->index(i, 0) directly. I don't see the point of it, but hey, it's possible :)
// implementation
class Adapter {
QAbstractItemModel* m_model;
public:
explicit Adapter(QComboBox & box) : m_model(box.model()) {}
explicit Adapter(QAbstractItemModel * model) : m_model(model) {}
QVariant operator[](int i) { return m_model->index(i, 0); }
};
// point of use
for( auto i = 0; i < myQComboBox->count(); i++ )
{
result[i] = Adapter(myQComboBox)[i];
}
A similar adapter could provide you with iterators.
You can retrieve items data using the combo box's model. Here is an example, how I would do that:
QComboBox combo;
combo.addItem("Item 1");
QAbstractItemModel *model = combo.model();
QModelIndex idx = model->index(0, 0); // Refers to the first item
QString item = model->data(idx).toString(); // Returns 'Item 1'
To access the second and further items of the combo box, just change the row number in index() function call:
QModelIndex idx = model->index(0, 0);
the row number ^
I am not aware of any iterators based API for combo boxes so far, but you can use all the strength of QAbstractItemModel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With