Пример #1
0
void HelpTreeWidget::openJsonDocument(const QString &filepath)
{
    QJsonDocument doc;
    QFile helpFile(filepath);
    if (!helpFile.open(QIODevice::ReadOnly)) {
        qWarning("Could not open pro file");
        return;
    }
    QByteArray jData = helpFile.readAll();
    helpFile.close();

    doc = QJsonDocument::fromJson(jData);
    QJsonObject obj = doc.object();
    QJsonArray jarray = obj["help"].toArray();

    for (int i = 0; i < jarray.size(); i++)
    {
        QString itemName = jarray.at(i).toObject()["name"].toString();
        QString itemDdsc = jarray.at(i).toObject()["dsc"].toString();

        QTreeWidgetItem *name = new QTreeWidgetItem();
        QTreeWidgetItem *dsc = new QTreeWidgetItem();
        name->setData(0, Qt::DisplayRole, itemName);
        dsc->setData(0, Qt::DisplayRole, itemDdsc);
        name->addChild(dsc);
        m_tree->addTopLevelItem(name);
    }
}
void EntityMap::loadData(QString ref)
{
    json = parseJSON(ref);
    QJsonArray enemyList = json["enemyList"].toArray();
    if(enemyList.size() > 0){
        for(int i = 0; i < enemyList.size(); i++){
            QJsonObject je = enemyList[i].toObject();

            EnemyEntry entry;
            entry.spawnTrigger = je["spawnTrigger"].toInt();
            entry.enemyClass = je["enemyClassName"].toString();
            entry.polarity = je["polarity"].toInt() % 2 == 0 ? WHITE : BLACK;
            entry.spawnX = je["spawnX"].toInt();
            entry.spawnY = je["spawnY"].toInt();

            QJsonArray pathList = je["paths"].toArray();
            for (int j = 0; j < pathList.size(); ++j) {
                QJsonArray path = pathList.at(j).toArray();
                entry.paths.append(Point(path.at(0).toInt(),path.at(1).toInt()));
            }

            entry.spawnRef = je["spawnRef"].toString();

            enemies.add(entry);

        }
    }
}
Пример #3
0
void MainWindow::parseReply(const QByteArray &data)
{
    QJsonObject json(QJsonDocument::fromJson(data).object());
    QString code = json.value("Code").toString("-99");
    QString desc = json.value("Desc").toString();

    QString opt;
    switch (_synchronizeType) {
    case STProductCreate:
        opt = tr("新增商品");
        if (code == "0")
        {
            /// 记录同步数据,并进行下一个跨境通同步
            QSqlQuery query;
            query.prepare(tr("update 数据同步 set 跨境通处理=1 "
                             "where 跨境通=1 and 同步指令='新增' and 同步表名='商品' and 同步主键KID=:id "));
            query.bindValue(":id", _currentLocalId);
            query.exec();
            _timer->start(1000);
//            synchronizeProductCreate();
        }
        break;
    case STOrderCreateKJTToERP:
        opt = tr("获取订单");
        _orderCreateKJTToERPData._replyData._code = code;
        _orderCreateKJTToERPData._replyData._desc = desc;
        if ("0" == code)
        {
            /// 读取订单id列表
            QJsonObject data = json.value("Data").toObject();
            _orderCreateKJTToERPData._total = data.value("Total").toInt();
            QJsonArray orderIdListArray = data.value("OrderIDList").toArray();
            QList<int> orderIdList;
            for (int i = 0; i < orderIdListArray.size(); i++)
                orderIdList.append(orderIdListArray.at(i).toInt());
            _orderCreateKJTToERPData._orderIdList = orderIdList;
            qDebug() << "orderIdList:" << _orderCreateKJTToERPData._orderIdList;

            _orderCreateKJTToERPData._currentIndex = 0;
            orderInfoBatchGet();
        }
        break;
    case STOrderInfoBatchGet:
        opt = tr("下载订单");
        /// 解析数据,写入ERP数据库,并继续请求数据
        if ("0" == code)
        {
            QJsonObject data = json.value("Data").toObject();
            QJsonArray orderListArray = data.value("OrderList").toArray();
            for (int i = 0; i < orderListArray.size(); i++)
                insertOrder2ERPByJson(orderListArray.at(i).toObject());
        }
        _timer->start(1000);
        break;
    default:
        break;
    }

    qInfo() << opt << code << desc;
}
Пример #4
0
void Config::loadLessons()
{
    clearLessons();
    QFile lessonsFile(resourcesPath() + "/baselessons/" + m_currentLayout->name + ".lsn");
    qDebug()<<"loding lessons from file: "<<resourcesPath() + "/baselessons/" + m_currentLayout->name + ".lsn";
    if( lessonsFile.open(QIODevice::ReadOnly) )
    {
        QJsonDocument jsonDoc = QJsonDocument::fromJson(lessonsFile.readAll());
        QJsonArray jsonArray = jsonDoc.array();
        for( int i = 0; i < jsonArray.count(); i++ )
        {
            Lesson *lesson = new Lesson;
            lesson->title = jsonArray.at(i).toObject().value("title").toString();
            lesson->author = jsonArray.at(i).toObject().value("author").toString();
            lesson->version = jsonArray.at(i).toObject().value("version").toString();
            lesson->content = jsonArray.at(i).toObject().value("content").toString();
            lesson->group = jsonArray.at(i).toObject().value("group").toString();

            m_lessons.append(lesson);
        }
        if( m_lessons.count() < 1 )
        {
            qDebug()<<"No lessons loaded!";
        }
    }
    else
    {
        qDebug()<<"Can't open lessons file!";
    }
}
QList<QString> SingleWeatherParamWidget::getDataFromJson(QString jsonStr){
    QList<QString> valueList;
    QJsonParseError jsonErr;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8(), &jsonErr);
    if(jsonErr.error == QJsonParseError::NoError){
        if(!jsonDoc.isEmpty()){
            if(jsonDoc.isObject()){
                QJsonObject jobj = jsonDoc.object();
                QJsonObject::iterator it = jobj.begin();
                while(it != jobj.end()){
                    if(QJsonValue::Array == it.value().type()){
                        QJsonArray array = it.value().toArray();
                        int subArrayCount = array.count();
                        for(int i = 0;i < subArrayCount;i++){
                            QJsonArray subArray = array.at(i).toArray();
                            valueList.append(subArray.at(0).toString());
                            valueList.append(subArray.at(1).toString());
                        }
                    }
                    it++;
                }
            }
        }
    }
    return valueList;
}
Пример #6
0
void TestWebChannel::testInvokeMethodConversion()
{
    QWebChannel channel;
    channel.connectTo(m_dummyTransport);

    QJsonArray args;
    args.append(QJsonValue(1000));

    {
        int method = metaObject()->indexOfMethod("setInt(int)");
        QVERIFY(method != -1);
        channel.d_func()->publisher->invokeMethod(this, method, args);
        QCOMPARE(m_lastInt, args.at(0).toInt());
    }
    {
        int method = metaObject()->indexOfMethod("setDouble(double)");
        QVERIFY(method != -1);
        channel.d_func()->publisher->invokeMethod(this, method, args);
        QCOMPARE(m_lastDouble, args.at(0).toDouble());
    }
    {
        int method = metaObject()->indexOfMethod("setVariant(QVariant)");
        QVERIFY(method != -1);
        channel.d_func()->publisher->invokeMethod(this, method, args);
        QCOMPARE(m_lastVariant, args.at(0).toVariant());
    }
}
Пример #7
0
void NetWork::dealGetListInfo(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray listObj = resultObj.find("tracks").value().toArray();

	QList<QStringList> rev_list;
	for (int i = 0; i < listObj.size(); i++)
	{
		QJsonObject mp3Obj = listObj.at(i).toObject();
		QString url = mp3Obj.find("mp3Url").value().toString();
		QString name = mp3Obj.find("name").value().toString();
		QJsonArray artistsList = mp3Obj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
		{
			QJsonObject artistsObjName = artistsList.at(j).toObject();
			artists.append(artistsObjName.find("name").value().toString() + " ");
		}
		QJsonObject albumObj = mp3Obj.find("album").value().toObject();
		QString album = albumObj.find("name").value().toString();
		int songId = mp3Obj.find("id").value().toInt();
		QStringList list;
		list << name << artists << album << url << QString::number(songId);
		rev_list.insert(i, list);
	}
	emit musicInfo(rev_list);
}
Пример #8
0
void SL::parsestops_json(QNetworkReply *reply) {
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "No connection in stoplist search";
        sender()->deleteLater();
        return;
    }

    QString strReply = (QString)reply->readAll();
    stops->clear();
    QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
    QJsonObject obj = jsonResponse.object();

    //qDebug() << obj["data"].toString();
    QJsonArray array = obj["data"].toArray();
    int count = 0;
    while(array.size() > count && count < 10) {
        if (!array.at(count).isObject()) {
            break;
        }
        QJsonObject elem = array.at(count).toObject();
        //qDebug() << "Name" << elem["Name"].toString() << "Id" << elem["SiteId"].toDouble();
        count++;
        QString id = QString::number(elem["SiteId"].toDouble());
        stops->append(elem["Name"].toString() + "#" + id);
    }
    emit stopsready("");
    sender()->deleteLater();
}
Пример #9
0
void NXMAccessManager::retrieveCredentials()
{
  qDebug("retrieving credentials");
  QNetworkRequest request(ToQString(GameInfo::instance().getNexusPage())
                          + QString("/Core/Libs/Flamework/Entities/User?GetCredentials&game_id=%1"
                                    ).arg(GameInfo::instance().getNexusGameID()));
  request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
  request.setRawHeader("User-Agent", userAgent().toUtf8());

  QNetworkReply *reply = get(request);
  QTimer timeout;
  connect(&timeout, &QTimer::timeout, [reply] () {
    reply->deleteLater();
  });
  timeout.start();

  connect(reply, &QNetworkReply::finished, [reply, this] () {
    QJsonDocument jdoc = QJsonDocument::fromJson(reply->readAll());
    QJsonArray credentialsData = jdoc.array();
    emit credentialsReceived(credentialsData.at(2).toString(),
                             s_PremiumAccountStates.find(credentialsData.at(1).toInt())
                                                         != s_PremiumAccountStates.end());
    reply->deleteLater();
  });

  connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
          [=] (QNetworkReply::NetworkError) {
    qDebug("failed to retrieve account credentials: %s", qPrintable(reply->errorString()));
    reply->deleteLater();
  });
}
Пример #10
0
void NetWork::dealSeach(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonObject resultObj = obj.find("result").value().toObject();
	QJsonArray objList = resultObj.find("songs").value().toArray();

	m_list.clear();
	m_songIds.clear();
	for (int i = 0; i < objList.count(); i++)
	{
		QJsonObject songObj = objList.at(i).toObject();
		int songId = songObj.find("id").value().toInt();
		QString name = songObj.find("name").value().toString();
		QJsonArray artistsList = songObj.find("artists").value().toArray();
		QString artists = "";
		for (int j = 0; j < artistsList.count(); j++)
			artists.append(artistsList.at(j).toObject().find("name").value().toString());
		QString album = songObj.find("album").value().toObject().find("name").value().toString();

		m_songIds.insert(songId, i);
		QStringList list;
		list << name << artists << album << "" << QString::number(songId);
		m_list.insert(i, list);
	}
}
Пример #11
0
QList<RemoteModelItem*> RemoteModelItem::loadArray(const QJsonValue& value, RemoteModelItem* parent)
{
    QList<RemoteModelItem*> items;

    // Loop through all directory items
    QJsonArray array = value.toArray();
    for(int i=0;i<array.size();i++)
    {
        // Create a new model item with the specified parent
        RemoteModelItem* item = new RemoteModelItem(parent);

        // Save all relevant values. If one of the values isn't set in the JSON document, an empty string
        // will be stored
        item->setValue(RemoteModelColumnName, array.at(i).toObject().value("name"));
        item->setValue(RemoteModelColumnType, array.at(i).toObject().value("type"));
        item->setValue(RemoteModelColumnUrl, array.at(i).toObject().value("url"));
        item->setValue(RemoteModelColumnCommitId, array.at(i).toObject().value("commit_id"));
        item->setValue(RemoteModelColumnSize, array.at(i).toObject().value("size"));
        item->setValue(RemoteModelColumnLastModified, array.at(i).toObject().value("last_modified"));

        items.push_back(item);
    }

    return items;
}
Пример #12
0
void VstSettings::read(const QJsonObject &in)
{
    foldersToScan.clear();
    if (in.contains("scanPaths")) {
        QJsonArray scanPathsArray = in["scanPaths"].toArray();
        for (int i = 0; i < scanPathsArray.size(); ++i)
            foldersToScan.append(scanPathsArray.at(i).toString());
    }
    cachedPlugins.clear();
    if (in.contains("cachedPlugins")) {
        QJsonArray cacheArray = in["cachedPlugins"].toArray();
        for (int x = 0; x < cacheArray.size(); ++x) {
            QString pluginFile = cacheArray.at(x).toString();
            if (QFile(pluginFile).exists()) // if a cached plugin is removed from the disk we need skip this file

                cachedPlugins.append(pluginFile);
        }
    }
    blackedPlugins.clear();
    if (in.contains("BlackListPlugins")) {
        QJsonArray cacheArray = in["BlackListPlugins"].toArray();
        for (int x = 0; x < cacheArray.size(); ++x)
            blackedPlugins.append(cacheArray.at(x).toString());
    }
}
Пример #13
0
static Nuria::JsonMetaObjectReader::Error parseMethodArgumentList (const QJsonArray &names, const QJsonArray &types,
								   QVector< QByteArray > &outNames,
								   QVector< QByteArray > &outTypes) {
	if (names.size () != types.size ()) {
		return Nuria::JsonMetaObjectReader::MethodArgumentsHaveDifferentLengths;
	}
	
	// 
	for (int i = 0; i < names.size (); i++) {
		QJsonValue curName = names.at (i);
		QJsonValue curType = types.at (i);
		
		if (!curName.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentNamesContainsNonString;
		if (!curType.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentTypesContainsNonString;
		
		// 
		outNames.append (curName.toString ().toLatin1 ());
		outTypes.append (curType.toString ().toLatin1 ());
		
	}
	
	// 
	return Nuria::JsonMetaObjectReader::NoError;
	
}
Пример #14
0
void AppModel::handleForecastNetworkData(QObject *replyObj)
{
    QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj);
    if (!networkReply)
        return;

    if (!networkReply->error()) {
        QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll());

        QJsonObject jo;
        QJsonValue jv;
        QJsonObject root = document.object();
        jv = root.value(QStringLiteral("list"));
        if (!jv.isArray())
            qWarning() << "Invalid forecast object";
        QJsonArray ja = jv.toArray();
        //we need 4 days of forecast -> first entry is today
        if (ja.count() != 5)
            qWarning() << "Invalid forecast object";

        QString data;
        for (int i = 1; i<ja.count(); i++) {
            WeatherData *forecastEntry = new WeatherData();

            //min/max temperature
            QJsonObject subtree = ja.at(i).toObject();
            jo = subtree.value(QStringLiteral("temp")).toObject();
            jv = jo.value(QStringLiteral("min"));
            data.clear();
            data += niceTemperatureString(jv.toDouble());
            data += QChar('/');
            jv = jo.value(QStringLiteral("max"));
            data += niceTemperatureString(jv.toDouble());
            forecastEntry->setTemperature(data);

            //get date
            jv = subtree.value(QStringLiteral("dt"));
            QDateTime dt = QDateTime::fromMSecsSinceEpoch((qint64)jv.toDouble()*1000);
            forecastEntry->setDayOfWeek(dt.date().toString(QStringLiteral("ddd")));

            //get icon
            QJsonArray weatherArray = subtree.value(QStringLiteral("weather")).toArray();
            jo = weatherArray.at(0).toObject();
            forecastEntry->setWeatherIcon(jo.value(QStringLiteral("icon")).toString());

            //get description
            forecastEntry->setWeatherDescription(jo.value(QStringLiteral("description")).toString());

            d->forecast.append(forecastEntry);
        }

        if (!(d->ready)) {
            d->ready = true;
            emit readyChanged();
        }

        emit weatherChanged();
    }
    networkReply->deleteLater();
}
Пример #15
0
void Config::loadGeneratedLessons()
{
    clearGeneratedLessons();
    QFile lessonsFile(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/generatedLessons/" + m_currentLayout->name + ".lsn");
    qDebug()<<"loding generated lessons from file: "<<QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/generatedLessons/" + m_currentLayout->name + ".lsn";
    if( lessonsFile.open(QIODevice::ReadOnly) )
    {
        QJsonDocument jsonDoc = QJsonDocument::fromJson(lessonsFile.readAll());
        QJsonArray jsonArray = jsonDoc.array();
        for( int i = 0; i < jsonArray.count(); i++ )
        {
            Lesson *lesson = new Lesson;
            lesson->title = jsonArray.at(i).toObject().value("title").toString();
            lesson->author = "lessons generator";
            lesson->version = "0.0.0";
            lesson->content = jsonArray.at(i).toObject().value("content").toString();

            m_generatedLessons.append(lesson);
        }
        if( m_generatedLessons.count() < 1 )
        {
            qDebug()<<"No generated lessons loaded!";
        }
    }
    else
    {
        qDebug()<<"Can't open generated lessons file!";
    }
}
Пример #16
0
bool LOCACC::deleteElement(QTreeWidgetItem *currentItem)
{
    QString elementId = currentItem->text(0);
    QJsonArray jArray = m_jsonMasterObj["locAccData"].toArray();
    QString parentScreen = currentItem->parent()->text(0);
    QJsonObject tempObj ;
    for(int i = 0 ; i < jArray.count() ; i++ )
    {
        tempObj = jArray.at(i).toObject();
        if(tempObj["id"] == parentScreen)
        {
            QJsonArray eleJArray = tempObj["elements"].toArray();
            QJsonObject eleObject ;
            for(int j = 0 ; j < eleJArray.count() ; j++)
            {
                eleObject = eleJArray.at(j).toObject();
                if(eleObject["id"] == elementId)
                {
                    eleJArray.removeAt(j);
                    tempObj["elements"] = eleJArray;
                    jArray.replace(i,tempObj);
                    break;
                }
            }
        }
    }
    m_jsonMasterObj["locAccData"] = jArray;
    currentItem->parent()->removeChild(currentItem);
    emptyTreeWidget(currentItem);
    writeFile();
    return true;
}
void EntryModel::read(const QJsonObject &json)
{
    beginResetModel();
    entryList.clear();

    QJsonArray enemyList = json["enemyList"].toArray();
    if(enemyList.size() > 0){
        for(int i = 0; i < enemyList.size(); i++){
            QJsonObject je = enemyList[i].toObject();

            EnemyEntry entry;
            entry.spawnTrigger = je["spawnTrigger"].toInt();
            entry.enemyClass = je["enemyClassName"].toString();
            entry.polarity = je["polarity"].toInt() % 2 == 0 ? WHITE : BLACK;
            entry.spawnX = je["spawnX"].toInt();
            entry.spawnY = je["spawnY"].toInt();

            QJsonArray pathList = je["paths"].toArray();
            for (int j = 0; j < pathList.size(); ++j) {
                QJsonArray path = pathList.at(j).toArray();
                entry.paths.append(Point(path.at(0).toInt(),path.at(1).toInt()));
            }

            entry.spawnRef = je["spawnRef"].toString();

            entryList.append(entry);
        }
    }
    endResetModel();

}
Пример #18
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QVariant DREAM3DSettings::value(const QString& key, const QVariant& defaultValue)
{
  if (m_Stack.top()->group.contains(key) == false)
  {
    return defaultValue;
  }

  if (m_Stack.top()->group[key].isArray())
  {
    QJsonArray jsonArray = m_Stack.top()->group[key].toArray();
    QString value = jsonArray.at(Value).toString();
    QString typeName = jsonArray.at(Type).toString();
    if (typeName == "QByteArray")
    {
      QByteArray byteArray8Bit = value.toLocal8Bit();
      QByteArray byteArray = QByteArray::fromBase64(byteArray8Bit);
      return byteArray;
    }
    else
    {
      return value;
    }
  }

  return m_Stack.top()->group.value(key).toVariant();
}
Пример #19
0
void Client::setCardFlag(const QJsonValue &pattern){
	QJsonArray texts = pattern.toArray();

	int card_id = texts.at(0).toDouble();
	QString object = texts.at(1).toString();

	Bang->getCard(card_id)->setFlags(object);
}
Пример #20
0
void FavoriteMenu::load(QMenu *menu, bool download)
{
    //一旦クリア
    menu->clear();

    QAction *action;
    QByteArray data;
    QFile file(FAVORITE_DOWNLOAD_FILE);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
    }else{
        QTextStream in(&file);
        in.setCodec("UTF-8");
        while(!in.atEnd()){
            data.append(in.readLine());
        }
        file.close();

        QJsonDocument json = QJsonDocument::fromJson(data);
        QJsonArray array = json.object().value("root").toArray();
        //フォルダ
        for(int i=0; i<array.count(); i++){
            //アイテム
            if(TO_VALUE(array.at(i), "array").isArray()){
                addItem(menu, TO_ARRAY(array.at(i)));
            }else{
//            qDebug() << "title:" << TO_STRING(array->at(i), KEY_TITLE);
                action = menu->addAction(TO_STRING(array.at(i), KEY_TITLE), this, SLOT(clickItem()));
                action->setData(TO_STRING(array.at(i), KEY_URL));
            }
        }

        //現状のデータの日付を保存
        m_currentLoadedFavDataDate = QDate::fromString(json.object().value("serial").toString().left(8), "yyyyMMdd");
//        qDebug() << json.object().value("serial").toString().left(8);
//        qDebug() << "serial=" << serial << "," << serial.toJulianDay();
//        qDebug() << "today =" << QDate::currentDate() << "," << QDate::currentDate().toJulianDay();

    }

    //ユーザー登録ぶん
    QSettings settings(FAV_FILE_NAME, FAV_FILE_FORMAT);
    settings.beginGroup(QStringLiteral(FAV_USER));
    QHash<QString, QVariant> list = settings.value(QStringLiteral(FAV_USER_BOOKMARK)).toHash();
    foreach (const QString &key, list.keys()) {
        action = menu->addAction(list.value(key).toString(), this, SLOT(clickItem()));
        action->setData(key);
    }
    settings.endGroup();


    //お気に入りをダウンロード
    if(download){
        updateFromInternet();
    }
}
Пример #21
0
void search::findinfile(){

    if(document->isEmpty()) {
        QFile file(":/city_data");
        if(file.open(QIODevice::ReadOnly)){
            QString citydata = file.readAll();
            //qDebug()<<citydata;
            QJsonParseError json_error;
            *document = QJsonDocument::fromJson(citydata.toUtf8(),&json_error);
            if(json_error.error != QJsonParseError::NoError) {
                qDebug()<<"json error"<<json_error.errorString();
                return;
            }
        }
        file.close();
    }
    //QString data = "[{\"s\":[true,1,5]},{\"s\":[true,1,5]}]";
    //qt 的 json不能解析{a:"xxx"}这种,只能{"a":"xxx"}这种key为字符串的json
    QJsonObject ob;
    QString n,p,pc,pv,fl;
    QJsonArray arr;
    if((!oldkey.isEmpty())&&(key.indexOf(oldkey)>-1 ))//继续输入时使用之前的结果,但减少不可以,因为tmp是不断更新的
    {
        arr = tmp;
        //qDebug()<<"arr = tmp";
    }
    else {
         arr = document->array();
         //qDebug()<<"arr = document->array()";
    }
    tmp = QJsonArray();//清空,准备储存新的结果
    for(int i=0;i<arr.count();i++)
    {
        ob = arr.at(i).toObject();
        n = ob.value("n").toString();
        p = ob.value("p").toString();//p和pc可以随便用
        pc = ob.value("pc").toString();
        pv = ob.value("pv").toString();
        fl = ob.value("fl").toString();
        p = n + p + pc + pv + fl;//p和pc可以随便用
        if(p.indexOf(key)!=-1)
        {
            //qDebug()<<"Found:"<<p;
            tmp +=arr.at(i);
            QListWidgetItem *item;
            item=new QListWidgetItem;
            item->setText(n + "-" + pv);
            item->setToolTip(ob.value("ac").toString());
            ui->listWidget->addItem(item);
        }
        //qDebug()<<"url:"<<ob.value("n");
    }

    oldkey = key;//备份当前搜索词
}
Пример #22
0
void Client::playSkillEffect(const QJsonValue &play_str){
	QJsonArray words = play_str.toArray();
	if(words.size() != 2){
		return;
	}

	QString skill_name = words.at(0).toString();
	int index = words.at(1).toDouble();

	Bang->playSkillEffect(skill_name, index);
}
Пример #23
0
QColor Config::getColor(const QString& name)
{
	QColor color;

	QJsonArray jArr = findKey(name).toArray();

	if (jArr.size() == 3)
		color.setRgb(jArr.at(0).toInt(), jArr.at(1).toInt(), jArr.at(2).toInt());

	return color;
}
Пример #24
0
Schema *MessageFacade::defineSchema(QJsonObject *root, ControllerNode *pControllerNode){
    QJsonValue jsonValue = root->value(SCHEMA);
    if (!jsonValue.isUndefined() && jsonValue.isObject()){
        QJsonObject schema= jsonValue.toObject();
        QJsonValue strings =schema.value(STRING_TYPE);
        QJsonValue ints =schema.value(INT_TYPE);
        QJsonValue primaryKey = schema.value(PRIMARY_KEY);
        if (!strings.isUndefined() && strings.isArray() &&!ints.isUndefined()
                && ints.isArray() && !primaryKey.isUndefined() && primaryKey.isObject()){
            QJsonArray columnaStringType = strings.toArray();
            QJsonArray columnaIntsType = ints.toArray();
            QJsonObject columnaPrimaryKey = primaryKey.toObject();
            bool success = true;
            QJsonObject currentObject;
            for (int x = 0; x < columnaStringType.size(); x++){
                currentObject =columnaStringType.at(x).toObject();
                success = success && currentObject.value(currentObject.keys().at(0)).isDouble();
            }
            for (int x = 0; x < columnaIntsType.size(); x++)success = success && columnaIntsType.at(x).isString();
            QString primaryKeyName =columnaPrimaryKey.keys().at(0);
            qDebug() << "validando....";
            if (success && validatingPrimaryKey(primaryKeyName,&columnaPrimaryKey)){
                qDebug() << "validacion completa el JSON es valido";
                Schema *dataSchema = StorageblockFacade::getInstance()->createSchema(1+columnaIntsType.size()+columnaStringType.size());
                unsigned int sizeOfBytes = 0;
                QJsonObject primaryKeyScheme;
                primaryKeyScheme = columnaPrimaryKey.value(primaryKeyName).toObject();
                if (primaryKeyName.compare(INT_TYPE) == 0)sizeOfBytes = sizeof(int);
                else sizeOfBytes = primaryKeyScheme.value(primaryKeyScheme.keys().at(0)).toInt()*sizeof(char);
                dataSchema->setSchemaOverColumn(0,primaryKeyScheme.keys().at(0).toStdString(),sizeOfBytes,
                (primaryKeyName.compare(INT_TYPE) == 0)?SchemeRow::INT_TYPE:SchemeRow::STRING_TYPE);
                int place= 1;
                for (int x = 0; x < columnaIntsType.size(); x++){
                    currentObject =columnaIntsType.at(x).toObject();
                    dataSchema->setSchemaOverColumn(x+(place++),columnaIntsType.at(x).toString().toStdString(),sizeof(int),SchemeRow::INT_TYPE);
                }
                for (int x = 0; x < columnaStringType.size(); x++){
                    currentObject =columnaStringType.at(x).toObject();
                    currentObject.value(currentObject.keys().at(0)).toString();
                    dataSchema->setSchemaOverColumn(x+place,currentObject.keys().at(0).toStdString(),sizeof(char)*currentObject.value(currentObject.keys().at(0)).toInt(),SchemeRow::STRING_TYPE);
                }
                SchemeRow row;
                QString type;
                for(int x = 0; x < dataSchema->getLenght();x++){
                    row = (*dataSchema)[x];
                    type= (row.getTypeRestrictor()==SchemeRow::INT_TYPE)?"int    ":"string";
                    qDebug() << "| type: "<< type<< "\t| name: " << row.toString().c_str() << "\t\t| size: \t"<< row.getByteSize();
                }
                return dataSchema;
            }
        }
    }
    return 0;
}
Пример #25
0
QJsonValue QMetaObjectPublisher::invokeMethod(QObject *const object, const int methodIndex,
                                              const QJsonArray &args)
{
    const QMetaMethod &method = object->metaObject()->method(methodIndex);

    if (method.name() == QByteArrayLiteral("deleteLater")) {
        // invoke `deleteLater` on wrapped QObject indirectly
        deleteWrappedObject(object);
        return QJsonValue();
    } else if (!method.isValid()) {
        qWarning() << "Cannot invoke unknown method of index" << methodIndex << "on object" << object << '.';
        return QJsonValue();
    } else if (method.access() != QMetaMethod::Public) {
        qWarning() << "Cannot invoke non-public method" << method.name() << "on object" << object << '.';
        return QJsonValue();
    } else if (method.methodType() != QMetaMethod::Method && method.methodType() != QMetaMethod::Slot) {
        qWarning() << "Cannot invoke non-public method" << method.name() << "on object" << object << '.';
        return QJsonValue();
    } else if (args.size() > 10) {
        qWarning() << "Cannot invoke method" << method.name() << "on object" << object << "with more than 10 arguments, as that is not supported by QMetaMethod::invoke.";
        return QJsonValue();
    } else if (args.size() > method.parameterCount()) {
        qWarning() << "Ignoring additional arguments while invoking method" << method.name() << "on object" << object << ':'
                   << args.size() << "arguments given, but method only takes" << method.parameterCount() << '.';
    }

    // construct converter objects of QVariant to QGenericArgument
    VariantArgument arguments[10];
    for (int i = 0; i < qMin(args.size(), method.parameterCount()); ++i) {
        QVariant arg = args.at(i).toVariant();
        if (method.parameterType(i) != QMetaType::QVariant && !arg.convert(method.parameterType(i))) {
            qWarning() << "Could not convert argument" << args.at(i) << "to target type" << method.parameterTypes().at(i) << '.';
        }
        arguments[i].value = arg;
    }

    // construct QGenericReturnArgument
    QVariant returnValue;
    if (method.returnType() != qMetaTypeId<QVariant>() && method.returnType() != qMetaTypeId<void>()) {
        // Only init variant with return type if its not a variant itself, which would
        // lead to nested variants which is not what we want.
        // Also, skip void-return types for obvious reasons (and to prevent a runtime warning inside Qt).
        returnValue = QVariant(method.returnType(), 0);
    }
    QGenericReturnArgument returnArgument(method.typeName(), returnValue.data());

    // now we can call the method
    method.invoke(object, returnArgument,
                  arguments[0], arguments[1], arguments[2], arguments[3], arguments[4],
                  arguments[5], arguments[6], arguments[7], arguments[8], arguments[9]);

    return wrapResult(returnValue);
}
Пример #26
0
void NetWork::dealSongId(QNetworkReply *reply)
{
	QJsonObject obj = getObject(*reply);
	if (obj.isEmpty())
		return;
	QJsonArray songObj = obj.find("songs").value().toArray();
	QString url = songObj.at(0).toObject().find("mp3Url").value().toString();
	int id = songObj.at(0).toObject().find("id").value().toInt();
	m_list[m_songIds.value(id)][3] = url;
	m_musicCount++;
	if (m_musicCount == m_songIds.count())
		emit musicInfo(m_list);
}
Пример #27
0
void SearchSuggester::handleReplyFinished()
{
	if (!m_networkReply)
	{
		return;
	}

	if (m_model)
	{
		m_model->clear();
	}

	m_networkReply->deleteLater();

	if (m_networkReply->size() <= 0)
	{
		m_networkReply = nullptr;

		return;
	}

	const QJsonDocument document(QJsonDocument::fromJson(m_networkReply->readAll()));

	if (!document.isEmpty() && document.isArray() && document.array().count() > 1 && document.array().at(0).toString() == m_query)
	{
		const QJsonArray completionsArray(document.array().at(1).toArray());
		const QJsonArray descriptionsArray(document.array().at(2).toArray());
		const QJsonArray urlsArray(document.array().at(3).toArray());

		m_suggestions.reserve(completionsArray.count());

		for (int i = 0; i < completionsArray.count(); ++i)
		{
			SearchSuggestion suggestion;
			suggestion.completion = completionsArray.at(i).toString();
			suggestion.description = descriptionsArray.at(i).toString();
			suggestion.url = urlsArray.at(i).toString();

			m_suggestions.append(suggestion);

			if (m_model)
			{
				m_model->appendRow(new QStandardItem(suggestion.completion));
			}
		}

		emit suggestionsChanged(m_suggestions);
	}

	m_networkReply = nullptr;
}
Пример #28
0
bool LOCACC::updateMessage(QStringList newMessageData, bool isAccTextSame, QTreeWidgetItem *currentItem)
{
    QString messageId = currentItem->text(0);
    QString eleId = currentItem->parent()->text(0);
    QJsonArray jArray = m_jsonMasterObj["locAccData"].toArray();
    QString parentScreen = currentItem->parent()->parent()->text(0);
    QJsonObject tempObj ;
    for(int i = 0 ; i < jArray.count() ; i++ )
    {
        tempObj = jArray.at(i).toObject();
        if(tempObj["id"] == parentScreen)
        {
            QJsonArray eleJArray = tempObj["elements"].toArray();
            QJsonObject tempEleObj;
            for(int j = 0 ; j < eleJArray.count(); j++)
            {
                tempEleObj = eleJArray.at(j).toObject();
                if(tempEleObj["id"] == eleId)
                {
                    QJsonArray msgsArray = tempEleObj["messages"].toArray();
                    QJsonObject tempMsgObj;
                    for(int k = 0; k < msgsArray.count() ; k++)
                    {
                        tempMsgObj = msgsArray.at(k).toObject();
                        if(tempMsgObj["id"] == messageId)
                        {
                            msgsArray.removeAt(k);
                            if(messageExistance(newMessageData,msgsArray))
                            {
                                return false;
                            }
                            QJsonObject newMsgObj = getMessageJson(newMessageData,isAccTextSame);
                            msgsArray.insert(k,newMsgObj);
                            tempEleObj["messages"] = msgsArray;
                            eleJArray.replace(j,tempEleObj);
                            tempObj["elements"] = eleJArray;
                            jArray.replace(i,tempObj);
                            setMessageTooltip(currentItem,newMsgObj);
                            break;
                        }
                    }
                }
            }
        }
    }
    m_jsonMasterObj["locAccData"] = jArray;
    currentItem->setText(0,newMessageData.at(0));
    writeFile();
    return true;
}
Пример #29
0
void GwtCallback::setBackgroundColor(QJsonArray rgbColor)
{
#if defined(NDEBUG) || !defined(_WIN32)
   // don't set the background color in win32 debug builds because Chromium can crash on a fatal assert in
   // debug builds when the background color is changed.
   // https://bitbucket.org/chromiumembedded/cef/issues/2144
   int red   = rgbColor.at(0).toInt();
   int green = rgbColor.at(1).toInt();
   int blue  = rgbColor.at(2).toInt();
   
   QColor color = QColor::fromRgb(red, green, blue);
   pOwner_->webPage()->setBackgroundColor(color);
#endif
}
Пример #30
0
void AnimationClip::loadAnimationFromUrl()
{
    // TODO: Handle remote files
    QString filePath = Qt3DRender::QUrlHelper::urlToLocalFileOrQrc(m_source);
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Could not find animation clip:" << filePath;
        setStatus(QAnimationClipLoader::Error);
        return;
    }

    // TODO: Convert to plugins
    // Load glTF or "native"
    if (filePath.endsWith(QLatin1String("gltf"))) {
        qCDebug(Jobs) << "Loading glTF animation from" << filePath;
        GLTFImporter gltf;
        gltf.load(&file);
        // TODO: Allow loading of a named animation from a file containing many
        m_name = gltf.animations().first().name;
        m_channels = gltf.createAnimationData();
    } else if (filePath.endsWith(QLatin1String("json"))) {
        // Native format
        QByteArray animationData = file.readAll();
        QJsonDocument document = QJsonDocument::fromJson(animationData);
        QJsonObject rootObject = document.object();

        // TODO: Allow loading of a named animation from a file containing many
        QJsonArray animationsArray = rootObject[QLatin1String("animations")].toArray();
        qCDebug(Jobs) << "Found" << animationsArray.size() << "animations:";
        for (int i = 0; i < animationsArray.size(); ++i) {
            QJsonObject animation = animationsArray.at(i).toObject();
            qCDebug(Jobs) << "Animation Name:" << animation[QLatin1String("animationName")].toString();
        }

        // For now just load the first animation
        // TODO: Allow loading a named animation from within the file analogous to QMesh
        QJsonObject animation = animationsArray.at(0).toObject();
        m_name = animation[QLatin1String("animationName")].toString();
        QJsonArray channelsArray = animation[QLatin1String("channels")].toArray();
        const int channelCount = channelsArray.size();
        m_channels.resize(channelCount);
        for (int i = 0; i < channelCount; ++i) {
            const QJsonObject group = channelsArray.at(i).toObject();
            m_channels[i].read(group);
        }
    } else {
        qWarning() << "Unknown animation clip type. Please use json or glTF 2.0";
        setStatus(QAnimationClipLoader::Error);
    }
}