QComboBox - Select no entry

iBent picture iBent · Jan 31, 2016 · Viewed 7.7k times · Source

I have a QComboBox on my ui and set the model like this:

QStringListModel* model = new QStringListModel;
QStringList stringlist;
stringlist << "Test1" << "Test2" << "Test3";

model->setStringList(stringlist);
ui->comboBox->setModel(model);

Now I want to change the current index to be none (so that I get a blank combo box).

I already tried setting the current index to -1 with ui->comboBox->setCurrentIndex(-1);, but that results to an index aout of range exeption in qlist:

ASSERT failure in QList<T>::operator[]: "index out of range", file F:/Qt/5.4/mingw491_32/include/QtCore/qlist.h, line 486

Answer

jpo38 picture jpo38 · Jan 31, 2016

Regular (not editable) QComboBox don't allow a state where "no item" is selected. The selection has to be valid all the time.

You will have to add an empty string item in first position, and you may want to check this topic to make this dummy item not selectable: https://stackoverflow.com/a/7633081/3336423


Edit: Actually, it looks like it's perfectly possible to set the selection to -1 for any combobox (editable or not). So there is no need to add an empty item as proposed above.