-1

I am trying to get the id of the record in the model from a QCombobox with findData(index), but when select a item, it retunrs -1. It has been working in another project, but this is the second one that doesn't work. Here's my code:

modAnfi = new QSqlTableModel(this);
modAnfi->setQuery("SELECT id, (nombres || ' ' || apellidos) as Nombre, nombres, apellidos FROM tbPersonas WHERE activo=1");
comboAnfitrion->setModel(modAnfi);
comboAnfitrion->setModelColumn(1);
comboAnfitrion->setEditable(true);
comboAnfitrion->completer()->setCompletionMode(QCompleter::PopupCompletion);

connect(comboAnfitrion, SIGNAL(currentIndexChanged(int)), this, SLOT(currentIndexChangeAnfitrion(int)));

and:

void controlReg::currentIndexChangeAnfitrion(int index)
{

    qDebug() << comboAnfitrion->findData(index); // -1
    qDebug()<< comboAnfitrion->itemData(1); // QVariant(Invalid) 
}

Thanks for your time, any help will be appreciated.

László Papp
  • 51,870
  • 39
  • 111
  • 135

2 Answers2

1

Check the QComboBox documentation; from the findData description, quoting:

Returns the index of the item containing the given data

Where you are passing index as the "given data". However, index is already an index in the combobox. But you're obviously not looking for an index (since you already have one).

I suspect you actually want to call the itemData method instead? That would retrieve the data associated with an element for a given index.

codeling
  • 11,056
  • 4
  • 42
  • 71
  • You're right about findData, and the docu says that i need itemData, but see my example, it shows invalid, now i see that whith Qt::DisplayRole it retunrs the index!! why? maybe the query? how do i especifie the column that has the primary key in the Combobox or... i donk know. Please help me. – karenrojaz27 Oct 21 '13 at 16:20
  • Sorry, i'll explain correctly: When i use just findData returns -1; findData with Qt::displayRole returns the index; when i use itemData returns QVariant(Invalid); AND when i use itemData with Qt::DisplayRole returns QVariant(Qstring, "Name And LastName"). I need the id of the selected item, how do i retrieve it? thank u very much. – karenrojaz27 Oct 21 '13 at 16:51
1

You have to use the model you assign to the comboBox, use the index to look for it: modAnfi->data(modAnfi->index( index, 0));

bluesky777
  • 400
  • 6
  • 23
  • Thank you, bluesky777, i don't know why itemData doesn't allways work for me, but with model->data, and passing the index, it works for me. Thanks to all. – karenrojaz27 Oct 23 '13 at 21:48