11

I need to get an QStringList or an array containing all QStrings in a QComboBox.

I can't find a QComboBox method that does this, in fact I can't even find a QAbstractItemModel method that does this.

Is this really my only option:

std::vector< QString > list( myQComboBox.count() );

for( auto i = 0; i < list.size(); i++ )
{
    list[i] = myQComboBox.itemText( i );
}
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    There is no such function, AFAK. Why don't you like the approach you use (iteration over all items in the combo box)? – vahancho Sep 18 '14 at 12:25
  • @vahancho I presume it to be quite wasteful, especially as the size of the `QComboBox` grows. – Jonathan Mee Sep 18 '14 at 12:28
  • But maybe storing the content of the combo box into another container is also wasteful? Why do you need that? This can explain, why there is no such function in the API. – vahancho Sep 18 '14 at 12:39
  • What does the container of values get you that the member function `QComboBox::itemText` cannot? – rubenvb Sep 18 '14 at 12:54
  • I am going to clear `myQComboBox` and repopulate it, I need to identify elements that have changed. – Jonathan Mee Sep 18 '14 at 13:14

3 Answers3

13

Your answer looks fine, but you could also use a QStringList instead of a vector.

QStringList itemsInComboBox; 
for (int index = 0; index < ui->combo_box->count(); index++)
    itemsInComboBox << ui->combo_box->itemText(index);
DowntownDev
  • 842
  • 10
  • 15
9

QAbstractItemModel can contain images, trees other kinds of data that can be kept in QVariant. That is why you can't get a QStringList from it. It is pointless.

However, there is a class QStringListModel inherited from QAbstractItemModel that is intended to keep strings. And as you can expect it has method stringList().

QComboBox allows you to change a default model which it uses to another one. By default it uses QStandardItemModel. Change it to a string list model after creating the combo box.

 QStringListModel* cbModel = new QStringListModel();
 comboBox->setModel(cbModel);

Now you can get what you want:

QStringList list = cbModel->stringList();
Ezee
  • 4,214
  • 1
  • 14
  • 29
2

Don't do a premature optimization. Your code is ok. You may use qobject_cast<QStandardItemModel*>(combo.model()); to get extended access to combobox data.

Also, you can implement your own QAbstractItemModel which will store data as QStringList, and provide access to it.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61