Important: Please read the Qt Code of Conduct -

How to set in a QCombobox the current item with a non viewed column of my model

  • Hello,

    I'm used in C# .Net to set a combobox current row with or an .item, or an .index or a .value.
    I find out that in Qt a QCombobox has a .currentIndex corresponding with the .index, the currentText is the .value but I don't find a way to set the .item.

    What I want to do is:

    • I have a combobox populated with a QTableModel with in each record a field "ID" and a field "Description"
    • I set my .setModelColumn(1); to make my "Description" the viewed data
    • now I want to set my current selected item in the combobox by the "ID" field of my model.

    Is there a way t do so?


  • Use an indexOf approach on your model and use setCurrentIndex(int index) on the result of that?

  • @Jeroen3

    That's my problem, wog can I find this index.

    I have a query result of

       ID   !   Description
         1  !  Jef
         2  ! Dave
         3  ! Harry
         5  ! Mary
         8  ! John
      ...   !   ...

    this is stored in my QSqlQueryModel

    so how can I find and set my combobox pointing at) the row with ID=3 while displaying column 1 (the Description)

  • Perhaps I don't explain it correctly. What I want to do is that the user can select in the whole table of descriptions, so the whole table has to be in the model.

    Instead of setting


    I want to use something like


    for the moment I do it this way:

        int val = 507;
        int indx = ui->cbxGemeente->findText( QString::number(val));

    As always the way from Brussels to Paris passing by Rome is a nice trip but much to long...

    So I think there must be a more efficient way to attain the same result.

  • Why can't you have your model spit out the relation between ID and Description?
    Since apparantly ID is not consistent with QComboBox::index.
    QString Gemeenten_model->getDescription(id)?

    // Returns index in table "WHERE 'ID'==id".
    int Gemeenten_model->getTableIndex(id)?
    ui->cbxGemeente->setCurrentIndex( model->getTableIndex(id) );

    Another option is to inherit QComboBox and expand the functionality of that.

  • @Jeroen3

    The value in my ID column of the model is not synchronized with the table-index (deleted records make that the sequence is broken.). and the value in the ID column is the only thing I have.

  • Yes. I noticed that.
    That's why I suggested to create a function that converts "ID" to the TableIndex of which you have column 1 attached to the QComboBox.
    Basically you just search for that "ID" in your model, and return the table index where is is found. For example:

       ID   !   Description
         1  !  Jef
         2  ! Dave
         3  ! Harry
         5  ! Mary
         8  ! John

    model->getTableIndex( 5 ) == 3
    If you're into the mood of doing things properly you might even return a QModelIndex.

Log in to reply