5

我有QComboBox一个QSqlQueryModel作为它的模型。该模型由 SELECT type_id, type FROM typeswhere type_idisint且 type 为 a的数据库构建varchar

I set the QComboBoxvisible 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_idand I don't know how to achieve that. 我不能在这里使用该currentIndex()功能,因为 的当前索引QComboBox对我来说没用。

我认为正确的功能是currentData(),但我无法弄清楚,如何从第一列获取数据......

4

3 回答 3

6

另一个“解决方案”。我想出了以下解决方法:首先我将可见列设置为0,检索type_id,然后将可见列设置回1

ui->comboType->setModelColumn(0);
int type_id = ui->comboType->currentText().toInt();
ui->comboType->setModelColumn(1);

我不知道这样做有多正确,但它确实有效。

编辑: 最后,我找到了解决方案。我只需要修改一点king_nak -s 答案。谢谢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();
于 2015-11-26T14:34:15.723 回答
4

您可以使用该currentIndex()方法。即使索引对您的应用程序没有意义,它也是底层模型中的行。您可以使用它从那里查询数据

尝试这个:

int row = myComboBox->currentIndex();
QModelIndex idx = myComboBox->rootModelIndex().child(row, 0); // first column
QVariant data = myComboBox->model()->data(idx);
int type_id = data.toInt();
于 2015-11-26T13:55:38.200 回答
0

还有另一种很好的获取方法id是使用QSqlRecord.

如果我们有mymodel组合框的模型(即),我们可以获取QSqlRecord选定行的模型(即),然后获取该记录所需的字段。

例子:

QSqlRecord r = mymodel->record(myComboBox->currentIndex());
int type_id = r.value("type_id").toInt();
于 2016-12-28T03:33:01.680 回答