QComboBox keep currentText after model update
Solved
General and Desktop
-
I've a couple of QComboBox widgets populated from a QStringListModel.
Every time I update the model, the QComboBox reset to the first index.
Example:
- Model is {1,2};
- Select 2 in the QComboBox;
- Add 3 to model. Now model is {1,2,3};
- Current text changes to 1;
Snippet Code:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); m_model.setStringList({"1","2"}); ui->comboBox->setModel(&model); } void MainWindow::on_pushButton_clicked() { QStringList newList = {"1","2","3"}; m_model.setStringList(newList); }
How to avoid the index from being reset?
-
The problem arises from the usage of the method
m_model.setStringList()
. The latter always clear the previous data, hence the index always reset upon its call.Solution:
Use
m_model.setStringList()
only in the constructor to init the model.After that manually insert the row on the model and set the data for the respective row. This can be achieved with a simple modification in the slot method.
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); m_model.setStringList({"1","2"}); ui->comboBox->setModel(&model); } void MainWindow::on_pushButton_clicked() { m_model.insertRow(model.rowCount()); m_model.setData(model.index(model.rowCount()-1), "3"); }
In the example above, "3" is appended to the list model without changing the current index from the QComboBox.