如何获得带有两列模型的QComboBox的当前值? [英] How to get the current value of a QComboBox with a model with two columns?

查看:470
本文介绍了如何获得带有两列模型的QComboBox的当前值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以QSqlQueryModel为模型的QComboBox.该模型是从具有以下内容的数据库中构建的: SELECT type_id, type FROM types,其中type_idint,类型是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆