Advertisement
Guest User

backend.cpp

a guest
Jan 18th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. #include "backend.h"
  2.  
  3. Backend::Backend(QQuickItem *parent) : QObject(parent) {
  4.     engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
  5.  
  6.     mainWindow = engine.rootObjects().value(0);
  7.     lvList = mainWindow->findChild<QObject*>("lvList");
  8.     btnRequest = mainWindow->findChild<QObject*>("btnRequest");
  9.  
  10.     engine.rootContext()->setContextProperty("backend", this);
  11.  
  12.     namRequest = new QNetworkAccessManager(this);
  13.     connect(namRequest, SIGNAL(finished(QNetworkReply*)), this, SLOT(slotRequestFinished(QNetworkReply*)));
  14. }
  15.  
  16. void Backend::makeRequest(int id) {
  17.     btnRequest->setProperty("enabled", "false");
  18.  
  19.     QString prepareRequest("https://api.vk.com/method/friends.get?user_id=" + QString::number(id) +
  20.                            "&order=hints&count=500&fields=photo_50");
  21.     qDebug(prepareRequest.toUtf8());
  22.     QNetworkRequest request(QUrl(prepareRequest.toUtf8()));
  23.     namRequest->get(request);
  24. }
  25.  
  26. void Backend::slotRequestFinished(QNetworkReply * reply) {
  27.     if (reply->error() != QNetworkReply::NoError) {
  28.         qDebug(reply->errorString().toUtf8());
  29.     } else {
  30.         QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll()); //Документ
  31.         QJsonObject jsonObj;
  32.         QJsonValue jsonVal;
  33.         QJsonArray jsonArr;
  34.         int count;
  35.  
  36.         jsonObj = jsonDoc.object();
  37.  
  38.         if (!jsonObj.isEmpty()) {
  39.             jsonVal = jsonObj.value("count");
  40.             if (!jsonVal.isNull()) {
  41.                 count = jsonVal.toInt();
  42.             }
  43.         }
  44.  
  45.         jsonArr = jsonDoc.object().value("items").toArray();
  46.         QMetaObject::invokeMethod(lvList, "clear");
  47.         for (int i=0; i<jsonArr.size(); i++) {
  48.             QVariantMap map;
  49.             QJsonObject fri;
  50.             fri = jsonArr[i];
  51.  
  52.             QString photo50 = fri.value("photo_50").toString();
  53.             QString name = fri.value("first_name").toString() + fri.value("last_name").toString();
  54.  
  55.             map.insert("lvImage", photo50);
  56.             map.insert("lvLabel", name);
  57.  
  58.             QMetaObject::invokeMethod(lvList, "append", Q_ARG(QVariant, QVariant::fromValue(map)));
  59.         }
  60.     }
  61.  
  62.     btnRequest->setProperty("enabled", "true");
  63.  
  64.     reply->deleteLater();
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement