问题
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...
回答1:
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();
回答2:
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();
回答3:
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();
来源:https://stackoverflow.com/questions/33939914/how-to-get-the-current-value-of-a-qcombobox-with-a-model-with-two-columns