QComboBox binding and returning selected value



  • Hi,

    I have two questions (1) How do I bind a return value and text , returned by QSqlQueryModel to a combo box and (2) access the value of the selected item.

    Below is my function to initialize the combobox

    Binding QSqlQueryModel to QComboBox:

    QSqlQuery sql("select id, title from coa_vals where parent_id is null;", db);
    QSqlQueryModel *model = new QSqlQueryModel();
    model->setQuery(sql);
    ui->cbParent->setModel(model);
    ui->cbParent->setModelColumn(1);
    ui->cbParent->show();
    

    Access the selected item's value.

    Below is my code to get the selected value (suppose to be the ID column) from the combo box which doesn't work.

    int row = index <0? ui->cbParent->currentIndex():index;
    QModelIndex idx = ui->cbParent->model()->index(row, 0);
    QVariant data = ui->cbParent->model()->data(idx);
    int catid = data.toInt();
    QString str = "select id, title, details from coa_values where parend_id = " + catid;
    

    This sql always prints as below without the value of ID.

    select id, title, details from coa_values where parent_id =

    What did I miss? I have gone through almost all suggestions found about QComboBox and couldn't work. Alternative is to ditch the model, do manual binding with text and value.


  • Lifetime Qt Champion

    Hi,

    Check the content of data, your toInt conversion might be failing.



  • Yep, made the below change (no idea why I didn't think earlier, could have saved 4 hours of my time) and it worked.

    int row = index <0? ui->cbParent->currentIndex():index;
    QModelIndex idx = ui->cbParent->model()->index(row, 0);
    QVariant data = ui->cbParent->model()->data(idx);
    
    QString str = "select id, title, details from coa_values where parend_id = " + data.toString();
    

    Question: Why does the integer conversion fail? I have noticed this a lot.


  • Lifetime Qt Champion

    I didn't realise one thing, you where trying to add an int to string which will not to what you think/want. So the toInt was likely successful however you string building technique was wrong.



  • Yep, you made me think. the below works. Thanks a lot. Learning to program after years of hiatus. so am a bit rusty I guess.

    QString str = "select id, title, details from coa_values where parend_id = ";
    str.append(QString::number(data.toInt()));
    

    So I guess, I should look to append rather than adding. Is there any other better way?


  • Lifetime Qt Champion

    There's no need for multiple conversion, your toString call was a correct manner to do that.

    Otherwise, you can use QString::arg to build the string.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.