15

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
iBent
  • 392
  • 1
  • 2
  • 18
  • You may create your own model, that will return an empty `QString()` for invalid indexes. Or just subclass a `QStringListModel` and override `data` method (and, possible, `index` method too). – Dmitry Sazonov Feb 01 '16 at 08:28
  • 4
    It looks like ui->comboBox->setCurrentIndex(-1); works perfectly fine. The crashes were caused by a fault in my code. – iBent Feb 03 '16 at 09:44

1 Answers1

15

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.

jpo38
  • 20,821
  • 10
  • 70
  • 151