Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current value of a QComboBox with a model with two columns?

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...

like image 687
Aba Avatar asked Nov 26 '15 13:11

Aba


2 Answers

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();
like image 68
Aba Avatar answered Sep 20 '22 03:09

Aba


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();
like image 40
king_nak Avatar answered Sep 19 '22 03:09

king_nak