Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved QComboBox keep currentText after model update

    General and Desktop
    qcombobox model widgets
    1
    2
    143
    Loading More Posts
    • 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
      Oshio last edited by

      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 Reply Quote 0
      • O
        Oshio last edited by Oshio

        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 Reply Quote 0
        • First post
          Last post