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...
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With