Fill Form QTableView JSON Array
I am working on a web service client where I can get an array of JSON objects and I want to populate them with a QTableView. JSON keys should be column headings and values ββshould be data for each row.
Example JSON array:
[{"ID": "1", "name": "Robotina", "type": "droid", "year": "1970"}, {"ID": "2", "name": "Astro Boy "," type ":" droid "," year ":" 2015 "}, {" id ":" 3 "," name ":" Terminator "," type ":" droid "," year ":" 2020 "}, {" ID ":" 4 "," name ":" Benders "," type ":" droid "," year ":" 3000 "}, {" ID ":" 5 "," name " : "C-3PO", "type": "droid", "year": "1978"}, {"ID": "6", "name": "R2D2", "type": "droid", "year ":" 1977 "}, {" id ":" 7 "," name ":" Mazinger Z "," type ":" droid "," year ":" 1987 "}, {" id ":" 8 "," name ":" Robocop "," type ":" droid "," year ":" 1987 "}, {" identifier ":" 9 "," name ":" WALL- "," type ":" mechanical "," year ":" 2200 "}, {" identifier ":" 10 "," name ":" EVA "," type ":" mechanical "," year ":" 2200 "}]8 "," name ":" Robocop "," type ":" droid "," year ":" 1987 "}, {" identifier ":" 9 "," name ":" WALL- "," type ": "mechanical", "year": "2200"}, {"identifier": "10", "name": "EVA", "type": "mechanical", "year": "2200"}]8 "," name ":" Robocop "," type ":" droid "," year ":" 1987 "}, {" identifier ":" 9 "," name ":" WALL- "," type ": "mechanical", "year": "2200"}, {"identifier": "10", "name": "EVA", "type": "mechanical", "year": "2200"}]mechanical "," year ":" 2200 "}]mechanical "," year ":" 2200 "}]
source to share
I had a similar problem as my Json request was returning as an array of hashes.
I put together a QJsonTableModel here: https://github.com/poulh/qjsontablemodel
QJsonTableModel::Header header;
header.push_back( QJsonTableModel::Heading( { {"title","Title"}, {"index","title"} }) );
header.push_back( QJsonTableModel::Heading( { {"title","Season"}, {"index","season"} }) );
header.push_back( QJsonTableModel::Heading( { {"title","Episode"}, {"index","episode"} }) );
header.push_back( QJsonTableModel::Heading( { {"title","Air Date"}, {"index","air_date"} }) );
episodes = new QJsonTableModel( header, this );
ui->episodeTableView->setModel( episodes );
QString json = "[{\"series\":\"Black Sails\",\"season\":1,\"episode\":1,\"title\":\"I.\",\"air_date\":\"2014-01-25\"},{\"series\":\"Black Sails\",\"season\":1,\"episode\":2,\"title\":\"II.\",\"air_date\":\"2014-02-01\"}]";
QJsonDocument jsonDocument = QJsonDocument::fromJson( json );
episodes->setJson( jsonDocument );
Then you can get the Json object for that string using QModelIndex. It will provide you with the whole Json object, no matter which cell you clicked on.
void TVTime::on_episodesTableView_doubleClicked(const QModelIndex &index)
{
QJsonObject object = episodes->getJsonObject( index );
qDebug() << object["title"];
}
Let me know if it works.
source to share