You have to use the model you assign to the comboBox, use the index to look for it:
modAnfi->data(modAnfi->index( index, 0));
QComboBox::findData() always returns -1
Question
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.
Solution
OTHER TIPS
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.