如何获得带有两列模型的QComboBox的当前值? [英] How to get the current value of a QComboBox with a model with two columns?
问题描述
我有一个以QSqlQueryModel
为模型的QComboBox
.该模型是从具有以下内容的数据库中构建的:
SELECT type_id, type FROM types
,其中type_id
是int
,类型是varchar
.
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
.
我用currentIndex()
函数,因为QComboBox
的当前索引对我来说是无用的.
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.
我认为正确的功能是currentData()
,但是我无法弄清楚如何从第一列中获取数据...
I think the correct function is the currentData()
, but I can't figure it out, how to get the data from the first column...
推荐答案
另一个解决方案".我想出了以下解决方法:首先,将可见列设置为0
,检索type_id
,然后将可见列设置回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.
最后,我找到了解决方案.我只需要修改 king_nak -s的答案即可.谢谢 king_nak !
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();
这篇关于如何获得带有两列模型的QComboBox的当前值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!