Editable QComboBox with empty edit text: Avoid automatic text change when model is modified
I’m trying to use the same model for multiple combo boxes. The user may select an existing item from the model, or enter a new one which will then be added to the model, thus being added to all combo boxes using that model.
The user may also leave the text field empty, and that seems to cause two problems:
1. When assigning an existing (non-empty) model to a new combo box, the edit text of that box is automatically filled with the first item of the model, instead of just remaining empty. While that’s a minor problem I can work around by reinitializing the edit text after setting the model, the second problem is causing me severe headaches:
2. Having assigned the same model to multiple combo boxes, empty edit texts of one box get automatically filled with model content when all items are removed and then a new item is added to the model within another combo box.
Is there any way to totally disable this auto-fill behaviour for a an empty line edit of an editable combo box?
The same issue also bugs me. Here is a sample code that reproduces the issue:
- MainWindow::MainWindow(QWidget *parent) :
- ui(new Ui::MainWindow)
- connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(displayCurrentIndex(int)));
- m_pModel = new QStandardItemModel(this);
- delete ui;
- void MainWindow::on_pushButton_clicked()
- int nRows = m_pModel->rowCount();
- m_pModel->setData(m_pModel->index(nRows, 0), QString("%1").arg(qrand()0));
- void MainWindow::on_pushButton_2_clicked()
- void MainWindow::displayCurrentIndex(int n)
The first time the pushButton is clicked the first row of m_pModel is inserted. That automatically changes the current index of the combo box to 0. Why? On every other pushButton press the index does not change. Only on the first click. Is this a bug? Is there any workaround?