Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Read JSON from LocalHost and Dynamically fill QTableWidget.
Forum Updated to NodeBB v4.3 + New Features

Read JSON from LocalHost and Dynamically fill QTableWidget.

Scheduled Pinned Locked Moved Solved General and Desktop
9 Posts 4 Posters 733 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Phamy1289
    wrote on last edited by
    #1

    I'm still new to qt. I have to get access to a json on a localhost from a database and fill a QTableWidget with data from the json. Is there a way to fill the QtableWidget dynamically? Right now, I'm having to using a for-loop to get access to IDs of the data via url. I'm filling th table dynamically, but it's tied to the for-loop. I guess it would be more accurate to ask if there was a way to read all the json data if I didn't know the number of unique IDs. Should I have use a while loop and if so what would be the condition, or is there a easier way to do it?

    //Filling Requirements table
        for(int i = 0; i < 100; i++)
        {
            int index = i + 1;
            mpTable->insertRow(msRow);
            mpCheckBox = new QCheckBox("Unselected");
            mpCheckBox->setTristate(true);
            mpCheckBox->setStyleSheet("margin-left:50%; margin-right:50%");
    
            connect(mpCheckBox, SIGNAL(stateChanged(int)), this, SLOT(onCheckState(int)));
            mpTable->setCellWidget(msRow, 0, mpCheckBox);
    
            QString count = QString::number(index);
            auto myUrl = mBaseUrl + count.toStdString();
    
            mHttpReqrmtAccess.SendRequest(myUrl,
                                          std::bind(&ScheduleAdvice::HandleReply, this, std::placeholders::_1));
        }
    
    void ScheduleAdvice::HandleReply(QNetworkReply *reply)
    {
        if(reply->error())
        {
            qDebug() << reply->errorString();
        }
        else
        {
            QByteArray answer = reply->readAll();
            // Store our byte aray as JSON and parse it.
            QJsonDocument doc = QJsonDocument::fromJson(answer);
    
            //Extract Requirement Values/Info using a JSON object
            // TODO: Make requirement class?
            // TODO: Finish during future tasks
            if(doc.isObject())
            {
                QJsonObject root = doc.object();
    
                QJsonArray countriesArray = root["countries"].toArray();
                QJsonArray aoisArray = root["aois"].toArray();
                QJsonArray nipfTopicsArray = root["nipfTopics"].toArray();
    
                for(auto it = root.begin(); it != root.end(); ++it)
                {
                    if(it.key() == "reqId")
                    {
                        QString reqIdString = it.value().toString();
                        mpTable->setItem(msRow, 1, new QTableWidgetItem(reqIdString));
                    }
                    else if(it.key() == "reqSource")
                    {
                        QString reqSourceName = it.value().toString();
                        mpTable->setItem(msRow, 2, new QTableWidgetItem(reqSourceName));
                    }
                    else if(it.key() == "priority")
                    {
                        QTableWidgetItem *item = new QTableWidgetItem();
    
                        int priorityVal = it.value().toInt();
                        item->setData(Qt::EditRole, priorityVal);
    
                        mpTable->setItem(msRow, 3, item);
                    }
                    else if(it.key() == "bin")
                    {
                       QString binName = it.value().toString();
                       mpTable->setItem(msRow, 4, new QTableWidgetItem(binName));
                    }
                    else if(it.key() == "classification")
                    {
                        QString classification = it.value().toString();
                        mpTable->setItem(msRow, 6, new QTableWidgetItem(classification));
                    }
                    else if(it.key() == "status")
                    {
                        QString status =it.value().toString();
                        mpTable->setItem(msRow, 7, new QTableWidgetItem(status));
                    }
                    else if(it.key() == "startDate")
                    {
                        QString startDate = it.value().toString();
                        mpTable->setItem(msRow, 8, new QTableWidgetItem(startDate));
                    }
                    else if(it.key() == "closeDate")
                    {
                        QString closeDate = it.value().toString();
                        mpTable->setItem(msRow, 9, new QTableWidgetItem(closeDate));
                    }
                    else if(it.key() == "poiCoverage")
                    {
                        QString poiCoverage = it.value().toString();
                        mpTable->setItem(msRow, 10, new QTableWidgetItem(poiCoverage));
                    }
                    else if(it.key() == "aois")
                    {
                        QJsonValue val;
                        QJsonObject obj;
                        QString aoisName;
    
                        for(int i = 0; i < aoisArray.size(); i++)
                        {
                            val = aoisArray.at(i);
                            obj = val.toObject();
    
                            if(i == aoisArray.size()-1)
                            {
                                aoisName.append(obj["name"].toString());
                            }
                            else
                            {
                                aoisName.append(obj["name"].toString() + ", ");
                            }
    
                            mpTable->setItem(msRow, 11, new QTableWidgetItem(aoisName));
                        }
                    }
                    else if(it.key() == "countries")
                    {
                        QJsonValue val;
                        QJsonObject obj;
                        QString countriesName;
    
                        for(int i = 0; i < countriesArray.size(); i++)
                        {
                            val = countriesArray.at(i);
                            obj= val.toObject();
    
                            if(i == countriesArray.size()-1)
                            {
                                countriesName.append(obj["name"].toString());
                            }
                            else
                            {
                                countriesName.append(obj["name"].toString() + ", ");
                            }
                        }
    
                        mpTable->setItem(msRow, 12, new QTableWidgetItem(countriesName));
                    }
                    else if(it.key() == "nipfTopics")
                    {
                        for(const QJsonValue &val : nipfTopicsArray)
                        {
                            QJsonObject obj = val.toObject();
                            QString nipfTopicName = obj["name"].toString();
                            mpTable->setItem(msRow, 13, new QTableWidgetItem(nipfTopicName));
                        }
                    }
                    else if(it.key() == "created")
                    {
                        QString created = it.value().toString();
                        mpTable->setItem(msRow, 14, new QTableWidgetItem(created));
                    }
                    else if(it.key() == "createdBy")
                    {
                        QString createdBy = it.value().toString();
                        mpTable->setItem(msRow, 15, new QTableWidgetItem(createdBy));
                    }
                    else if(it.key() == "organization")
                    {
                        QString organization = it.value().toString();
                        mpTable->setItem(msRow, 16, new QTableWidgetItem(organization));
                    }
                    else if(it.key() == "lastUpdated")
                    {
                        QString lastUpdated = it.value().toString();
                        mpTable->setItem(msRow, 17, new QTableWidgetItem(lastUpdated));
                    }
                    else if(it.key() == "lastUpdatedBy")
                    {
                        QString lastUpdatedBy = it.value().toString();
                        mpTable->setItem(msRow, 18, new QTableWidgetItem(lastUpdatedBy));
                    }
                    else if(it.key() == "collectionReq")
                    {
                        QString collectionReq = it.value().toString();
                        mpTable->setItem(msRow, 19, new QTableWidgetItem(collectionReq));
                    }
                    else if(it.key() == "comments")
                    {
                        QString comments = it.value().toString();
                        mpTable->setItem(msRow, 20, new QTableWidgetItem(comments));
                    }
                    else
                    {
                        int randPercent = rand() %101;
                        QTableWidgetItem *percent = new QTableWidgetItem;
                        percent->setData(Qt::EditRole, randPercent);
                        mpTable->setItem(msRow, 5, percent);
                    }
                }
            }
            else// doc.isNull || doc.isEmpty
            {
                std::cout  << "Response is Empty or Not Valid JSON\n";
                return;
            }
    
            msRow++;
        }    
    }
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      @Phamy1289 said in Read JSON from LocalHost and Dynamically fill QTableWidget.:

      Right now, I'm having to using a for-loop to get access to IDs of the data via url

      What do you mean by that ?
      How do you know when you have exhausted all the IDs ?

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      P 1 Reply Last reply
      0
      • SGaistS SGaist

        Hi,

        @Phamy1289 said in Read JSON from LocalHost and Dynamically fill QTableWidget.:

        Right now, I'm having to using a for-loop to get access to IDs of the data via url

        What do you mean by that ?
        How do you know when you have exhausted all the IDs ?

        P Offline
        P Offline
        Phamy1289
        wrote on last edited by
        #3

        @SGaist After so many entries, the rest of come up with null attributes. Obviously, there are more just with empty attributes and could be filled in later. That's the problem I want to solve. I want to be able to go through all of the data where the IDs are not empty. If the IDs are not NULL then it's safe to assume it's a valid entry.

        VRoninV 1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          Can't the service you are calling give you that information ?

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          0
          • P Phamy1289

            @SGaist After so many entries, the rest of come up with null attributes. Obviously, there are more just with empty attributes and could be filled in later. That's the problem I want to solve. I want to be able to go through all of the data where the IDs are not empty. If the IDs are not NULL then it's safe to assume it's a valid entry.

            VRoninV Offline
            VRoninV Offline
            VRonin
            wrote on last edited by
            #5

            @Phamy1289 said in Read JSON from LocalHost and Dynamically fill QTableWidget.:

            I want to be able to go through all of the data where the IDs are not empty.

            I probably misunderstood but doesn't the below achieve this?

            if(it.key() == "reqId")
            {
                QString reqIdString = it.value().toString();
            if(reqIdString.isEmpty()) continue; // add this!
                mpTable->setItem(msRow, 1, new QTableWidgetItem(reqIdString));
            }
            

            "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
            ~Napoleon Bonaparte

            On a crusade to banish setIndexWidget() from the holy land of Qt

            1 Reply Last reply
            0
            • P Offline
              P Offline
              Phamy1289
              wrote on last edited by
              #6

              The problem is, the for-loop goes to the url of each of the individual JSONs. i.e https://localhost:8080/my/url/index, where index is 1-100. That's the issue that I'm having. I'm not messed with JSON before let alone trying to access it from a localhost DB.

              JonBJ 1 Reply Last reply
              0
              • P Phamy1289

                The problem is, the for-loop goes to the url of each of the individual JSONs. i.e https://localhost:8080/my/url/index, where index is 1-100. That's the issue that I'm having. I'm not messed with JSON before let alone trying to access it from a localhost DB.

                JonBJ Online
                JonBJ Online
                JonB
                wrote on last edited by JonB
                #7

                @Phamy1289
                I read your post yesterday and struggled to understand what your situation is/what you are asking, and I still struggle today :)

                I think you are saying you have an array/list of objects in your JSON, but you don't know how many. And at present your are using a for loop, where you do not know how many total elements there are, and that is a problem?

                So let's start with some basics.

                The fact that your JSON emanates from "a localhost from a database" is neither here nor there. JSON is JSON, wherever it comes from.

                You (correctly) seem to read the whole of the JSON into a QJsonDocument. (Make sure wherever you call this from all of the JSON is in the reply->readAll(), else you will need to buffer/accumulate all the input before being able to do this.)

                Now, if somewhere in the JSON it has an array/list, it will look like:

                [
                    ...,
                    ..., 
                    ...
                ]
                

                I do not care what the ...s are, they could be as simple or complex as you like, the point is they would be enclosed in [ ... ], if it is a list/array. When that is parsed you get a QJsonArray, and that has a count() method which tells you how many elements. So a for loop to visit them would go from 0 to count() - 1.

                I am not sure whether the above is where you are having difficulty. You don't show sample JSON which you are having trouble dealing with, so I'm not sure whether that is where you are stuck?

                1 Reply Last reply
                2
                • P Offline
                  P Offline
                  Phamy1289
                  wrote on last edited by
                  #8

                  I understand it better now and I figured it out. I had to make a static variable Row and just use the QTableWidget appendRow function. Sorry for all the confusion and thanks for all your help

                  1 Reply Last reply
                  0
                  • SGaistS Offline
                    SGaistS Offline
                    SGaist
                    Lifetime Qt Champion
                    wrote on last edited by
                    #9

                    Why a static variable ?

                    Interested in AI ? www.idiap.ch
                    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                    1 Reply Last reply
                    0

                    • Login

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • Users
                    • Groups
                    • Search
                    • Get Qt Extensions
                    • Unsolved