Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QComboBox keep currentText after model update

QComboBox keep currentText after model update

Scheduled Pinned Locked Moved Solved General and Desktop
qcomboboxmodelwidgets
2 Posts 1 Posters 778 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • O Offline
    O Offline
    Oshio
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0
    • O Offline
      O Offline
      Oshio
      wrote on last edited by Oshio
      #2

      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.

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved