5

I have a QComboBox with a QSqlQueryModel as its model. The model is constructed from a database with SELECT type_id, type FROM types where type_id is int and type is a varchar.

I set the QComboBox visible column with the setModelColumn(1) function, to see the actual types, instead of the indexes, but when a value is selected, I need to retrieve the type_id and I don't know how to achieve that. I can't use here the currentIndex() function, because the current index of the QComboBox is useless for me.

I think the correct function is the currentData(), but I can't figure it out, how to get the data from the first column...

Aba
  • 673
  • 6
  • 11

3 Answers3

7

Another "solution". I came up with the following workaround: First I set the visible column to 0, retrieve the type_id, then set back the visible column to 1.

ui->comboType->setModelColumn(0);
int type_id = ui->comboType->currentText().toInt();
ui->comboType->setModelColumn(1);

I don't know how correct is to do this way, but it works.

EDIT: Finally, I found the solution. I just needed to modify a bit king_nak-s answer. Thank you king_nak!

int row = myComboBox->currentIndex();
QModelIndex idx = myComboBox->model()->index(row, 0); // first column
QVariant data = myComboBox->model()->data(idx);
int type_id = data.toInt();
Aba
  • 673
  • 6
  • 11
4

You can use the currentIndex() method. Even if the index does not make sense for your application, it is the row in the underlying model. You can use it to query the data from there

Try this:

int row = myComboBox->currentIndex();
QModelIndex idx = myComboBox->rootModelIndex().child(row, 0); // first column
QVariant data = myComboBox->model()->data(idx);
int type_id = data.toInt();
king_nak
  • 11,313
  • 33
  • 58
  • I wanted to use your snippet, but it don't work. The `data` contains an invalid `QVariant` and the `type_id` is always `0`. – Aba Jan 07 '16 at 08:26
0

There is another pretty way of getting the id and that is using QSqlRecord.

If we have the model (i.e. mymodel) for the combobox, we can get the QSqlRecord for the selected row and then the fields we need for that record.

Example:

QSqlRecord r = mymodel->record(myComboBox->currentIndex());
int type_id = r.value("type_id").toInt();
Tarod
  • 6,732
  • 5
  • 44
  • 50