Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Create QComboBox Model from a JSON



  • Hi all,

    I'm developing a desktop app which uses a few comboxes.

    I use SetModel for a sql query to list elements in them like this:

    qry_tareas->prepare("SELECT chrDescProyecto FROM EjecucionProyectos_Proyectos WHERE ProyectoPredefinido IS NOT NULL");
        if(!qry_tareas->exec()){
             qDebug() << "Error...";
        }
        tareas_predefinidas->setQuery(*qry_tareas);
        ui->tareas_predefinidas->setModel(tareas_predefinidas);
    

    The thing is, is it possible for a JSonObject like this:

    {"data":[
    	{"id":319497680631052,"gid":"319497680631052","name":"AAOR-BAPA","resource_type":"project"},
    	{"id":921470089661507,"gid":"921470089661507","name":"Sira-2","resource_type":"project"},
    	{"id":933418298503073,"gid":"933418298503073","name":"PDL-Estructura Javier NC","resource_type":"project"}
    ]}
    

    To take keyValue "name" for a ┬┐combobox?

    I would like not to lose the reference of the JSON because I will need keyValue "gid" near future...

    regards,

    Dani.



  • So you want a QComboBox that shows all gid values in a list?



  • Hi @VRonin ,

    I want all "name" fields in a QComboBox, but if its possible I dont want to lose "gid" reference cause its the only way I have to perform request to the API.

    Once user selects one proyect, I will perform requests using the gid.

    Sorry for the bad explanation.

    Regards,

    Dani.



  • QAbstractItemModel *m_comboModel = new QStandardItemModel(this);
     // QJsonObject source
    sourceArray = source[QLatin1String("data")].toArray();
    m_comboModel->insertColumns(0,4);
    m_comboModel->insertRows(0,sourceArray.count());
    for(int i = 0;i!=sourceArray.count();++i){
    const auto rowObject = sourceArray.at(i)->toObject();
    m_comboModel->setData(m_comboModel->index(i,0), rowObject[QLatin1String("name")].toString());
    m_comboModel->setData(m_comboModel->index(i,1), rowObject[QLatin1String("gid")].toString());
    m_comboModel->setData(m_comboModel->index(i,2), rowObject[QLatin1String("id")].toString());
    m_comboModel->setData(m_comboModel->index(i,3), rowObject[QLatin1String("resource_type")].toString());
    }
    comboBox->setModel(m_comboModel);
    

    No you can just check the second column using the row from the combobox index to get the "gid" value



  • Hi @VRonin ,

    Damn, that was... fast!!!!!

    Thank you very much! It worked like a charm...

    Now I have to debug a little bit to understand the code ahahahahaha

    Thanks again!

    Regards!!!

    Dani!


Log in to reply