PDA

View Full Version : Qcombobox Binding With text and id ???



sai_3289
15th December 2012, 05:18
For a combobox i have added list of items using query from database table.
query.exec("select bookname from books_totallist");
while(query.next())
{
ui->comboBoxbook->addItem(query.value(0).toString());
}
Now Say combobox contains items as book1,book2,book3,.....etc.Each book has corresponding id in table.
If i select any book i need to get respective id of the book..? So please provide me some hint on this............



Regards
sai

pkj
15th December 2012, 06:52
QComboBox::addItem ( const QString & text, const QVariant & userData = QVariant() )
Let the text be the same as what you added. Also add the id [say query.value(1)] . Now use functions like QComboBox::itemData ( int index, int role = Qt::UserRole ) const to get Id.
Go through the QComboBox documentation and find related functions.

anda_skoa
15th December 2012, 17:27
You could also experiment with using a QSqlQueryModel and setting that as the model of QComboBox.

Cheers,
_

sai_3289
18th December 2012, 06:31
Yeah i have done that in same way.....Below is my code..
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery("SELECT bookID,bookName FROM books_totallist");
model->setHeaderData(0,Qt::Horizontal, tr("Book_ID"));
model->setHeaderData(1, Qt::Horizontal, tr("Book_Name"));
QTableView *view = new QTableView;
view->setSelectionBehavior(QAbstractItemView::SelectRows );
view->setSelectionMode(QAbstractItemView::SingleSelectio n);
ui->authorsComboBox->setModel(model);
ui->authorsComboBox->setView(view);
//view->setColumnHidden(0, true); --------->>here now for my combobox i am hidding " id coloumn " ....SO that showing only names in combobox.
Now if we select any bookname,i need to get the corresponding id of that...?How could this be acheived ????

ChrisW67
18th December 2012, 06:45
Use QComboBox::currentIndex() to get the model row number, then use the model's index() and data() to get the id column value.

You should not need a custom view for the combo box if you are only showing one column from a multi-column model. Try QComboBox::setModelColumn().