Get the contents of the QComboBox

I need to get QStringList

or an array containing everything QString

in QComboBox

.

I cannot find a method QComboBox

that does this, in fact I cannot even find a method QAbstractItemModel

that does this.

This is really my only option:

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

for( auto i = 0; i < list.size(); i++ )
{
    list[i] = myQComboBox.itemText( i );
}

      

+3


source to share


3 answers


QAbstractItemModel

can contain images, trees and other types of data that can be stored in QVariant

. This is why you cannot get QStringList

from it. It is pointless.

However, there is a class QStringListModel

inherited from QAbstractItemModel

that is designed to store strings. And as you might expect, it has a method stringList()

.

QComboBox

allows you to change the default model it uses for another. The default is QStandardItemModel

. Change it to the 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();

      

+3


source


Don't do premature optimization. Your code is fine. You can use qobject_cast<QStandardItemModel*>(combo.model());

combobox to get rich data access.



Alternatively, you can implement your own QAbstractItemModel, which will store the data as a QStringList and give it access.

+2


source


Your answer looks good, but you can 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);

      

+2


source







All Articles