gpt4 book ai didi

c++ - 来自数据库的 QT ComboBox ItemData

转载 作者:行者123 更新时间:2023-11-28 06:31:39 25 4
gpt4 key购买 nike

我有以下代码将 QT QComboBox 链接到我的 sqlite 数据库,它运行良好。但是在我的数据库中,我有与外键链接的类别和项目表。因此,当我从 QComboBox 中提取信息时,我需要获取 Category_ID 而不是框中列出的名称。我将如何使用模型将 QComboBox ItemData 设置为 Category_ID 字段,或者更好的是使用模型将 QComboBox ItemData 设置为我的类别对象?

谢谢,

void MainWindow::populatCat()
{
QSqlQueryModel *model = new QSqlQueryModel();
QString sql;
sql = "select Category_Name From Category ORDER BY Category_Name ASC;";
QSqlQuery* query = new QSqlQuery(db);
query->prepare(sql);
if(!query->exec()){
qDebug () << "Query Erorr: " << query->lastError();
}else{
qDebug () << "Query Successful: " << query->lastQuery();
}
model->setQuery(*query);
ui->cboCat->setModel(model);
}

最佳答案

好的,我现在就给出答案。 :)

QComboBox* myBox = new QComboBox();
connect( myBox, SIGNAL( indexChanged( int ) ), this, SLOT( handleIndexChange( int ) ) );

void myObject::handleIndexChange( int /*index*/ ) {
// We actually don't need the index
QComboBox* box = qobject_cast<QComboBox*>( sender() );
if ( box ) {
QVariant data = box->currentData(); // do whatever w/ data... sounds like call toInt() in your case.
}
}

我的所有三种方法的本质是,您必须做一些额外的事情来获取与更改后的当前项目相对应的 data()。如果它发出一个以底层数据为参数的信号,那就太好了,但这可能会变得昂贵。

关于c++ - 来自数据库的 QT ComboBox ItemData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27428280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com