当前位置: 首页>>代码示例>>C++>>正文


C++ QVariantList::count方法代码示例

本文整理汇总了C++中QVariantList::count方法的典型用法代码示例。如果您正苦于以下问题:C++ QVariantList::count方法的具体用法?C++ QVariantList::count怎么用?C++ QVariantList::count使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QVariantList的用法示例。


在下文中一共展示了QVariantList::count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: formatString

/*
    Generate a string given a value, using formatting defined within this class.
*/
QString QEStringFormatting::formatString( const QVariant& value ) const
{
    QEStringFormatting* self = (QEStringFormatting*) this;   // this works as modified members are just used as temp. variables.
    QString result;

    if( value.type() != QVariant::List ){
        // "Simple" scalar
        result = self->formatElementString( value );

    } else {
        // Array variable
        const QVariantList valueArray = value.toList();
        const int number = valueArray.count ();

        switch( arrayAction ) {

            case APPEND:
                // Interpret each element in the array as an unsigned integer and append
                // string representations of each element from the array with a space in
                // between each.
                for( int j = 0; j < number; j++ ){
                    QVariant element = valueArray.value (j);
                    QString elementString;
                    elementString = self->formatElementString( element );

                    if( j > 0 )result.append ( " " );
                    result.append( elementString );
                }
                break;

            case ASCII:
                // Interpret each element from the array as a character in a string.
                // Translate all non printing characters to '?' except for trailing
                // zeros (ignore them)
                for( int j = 0; j < number; j++ ){
                    QVariant element = valueArray.value( j );
                    bool okay;

                    int c = element.toInt( &okay );

                    if( !okay || (c == 0) ) break;  // Not an int or got a zero - end of string.

                    // Ignore carriage returns.
                    // Note this will cause problems when implementing on Commodore 8-bit machines,
                    // Acorn BBC, ZX Spectrum, and TRS-80 as they don't use a line feed.
                    if( c == '\r' )
                    {
                    }
                    // Translate all non printing characters (except for space and line feed) to a '?'
                    else if( (c!= '\n') && (c < ' ' || c > '~') )
                    {
                        result.append( "?" );
                    }
                    // Use everything else as is.
                    else
                    {
                        result.append( element.toChar() );
                    }
                }
                break;

            case INDEX:
                // Interpret the element selected by setArrayIndex().
                if( arrayIndex < (unsigned int)(number) )
                {
                    QVariant element = valueArray.value ((int) arrayIndex);
                    result = self->formatElementString( element );
                }
                break;

            default:
                self->formatFailure( QString ( "Invalid arrayAction: %d" ).arg ( (int) arrayAction ));
                result = "---";
                break;
        }
    }

    // Add units if required, if there are any present, and if the text is not an error message
    int eguLen = dbEgu.length(); // ??? Why cant this be in the 'if' statement? If it is it never adds an egu
    if( addUnits && eguLen && (format != FORMAT_TIME) )
    {
        result.append( " " ).append( dbEgu );
    }

   return result;
}
开发者ID:rorydog1,项目名称:epics,代码行数:89,代码来源:QEStringFormatting.cpp

示例2: testDeltaTByEspenakMeeus

void TestDeltaT::testDeltaTByEspenakMeeus()
{
	// test data from http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html#tab1
	QVariantList data;

	data << -500  << 17190 << 430;
	data << -400  << 15530 << 390;
	data << -300  << 14080 << 360;
	data << -200  << 12790 << 330;
	data << -100  << 11640 << 290;
	data << 0     << 10580 << 260;
	data << 100   << 9600  << 240;
	data << 200   << 8640  << 210;
	data << 300   << 7680  << 180;
	data << 400   << 6700  << 160;
	data << 500   << 5710  << 140;
	data << 600   << 4740  << 120;
	data << 700   << 3810  << 100;
	data << 800   << 2960  << 80;
	data << 900   << 2200  << 70;
	data << 1000  << 1570  << 55;
	data << 1100  << 1090  << 40;
	data << 1200  << 740   << 30;
	data << 1300  << 490   << 20;
	data << 1400  << 320   << 20;
	data << 1500  << 200   << 20;
	data << 1600  << 120   << 20;
	data << 1700  << 9     << 5;
	data << 1750  << 13    << 2;
	data << 1800  << 14    << 1;
	data << 1850  << 7     << 1;
	data << 1900  << -3    << 1;
	data << 1950  << 29    << 0.1;
	data << 1955  << 31.1  << 0.1;
	data << 1960  << 33.2  << 0.1;
	data << 1965  << 35.7  << 0.1;
	data << 1970  << 40.2  << 0.1;
	data << 1975  << 45.5  << 0.1;
	data << 1980  << 50.5  << 0.1;
	data << 1985  << 54.3  << 0.1;
	data << 1990  << 56.9  << 0.1;
	data << 1995  << 60.8  << 0.1;
	data << 2000  << 63.8  << 0.1;
	data << 2005  << 64.7  << 0.1;

	while(data.count() >= 3) 
	{
		int year = data.takeFirst().toInt();				
		int yout, mout, dout;
		double JD;
		double expectedResult = data.takeFirst().toDouble();
		double acceptableError = data.takeFirst().toDouble();		
		StelUtils::getJDFromDate(&JD, year, 1, 1, 0, 0, 0);
		double result = StelUtils::getDeltaTByEspenakMeeus(JD);
		double actualError = qAbs(qAbs(expectedResult) - qAbs(result));
		StelUtils::getDateFromJulianDay(JD, &yout, &mout, &dout);
		QVERIFY2(actualError <= acceptableError, QString("date=%2 year=%3 result=%4 expected=%5 error=%6 acceptable=%7")
							.arg(QString("%1-%2-%3 00:00:00").arg(yout).arg(mout).arg(dout))
							.arg(year)
							.arg(result)
							.arg(expectedResult)
							.arg(actualError)
							.arg(acceptableError)
							.toUtf8());
	}
}
开发者ID:NGCyang,项目名称:stellarium,代码行数:66,代码来源:testDeltaT.cpp

示例3: setupLevel

void ApplicationUI::setupLevel(const QVariantMap &levelData)
{
	if (m_map) {
		delete m_map;
	}
	if (m_robot) {
		delete m_robot;
	}
	while (!m_functions.empty()) {
		Function *f = m_functions[0];
		m_functions.removeFirst();
		delete f;
	}
	while (!m_stack.empty()) {
		FunctionRunner *f = m_stack.pop();
		delete f;
	}

	m_mapArea = m_gamePage->findChild<Container*>("mapArea");
	if (!m_mapArea) {
		qDebug("Failed to find map area");
		return;
	}
	m_mapArea->removeAll();

	int width = levelData["width"].toInt();
	int height = levelData["height"].toInt();
	int startX = levelData["startX"].toInt();
	int startY = levelData["startY"].toInt();
	QString direction = levelData["startDir"].toString();
	int endX = levelData["endX"].toInt();
	int endY = levelData["endY"].toInt();
	QVariantList mapData = levelData["data"].toList();
	int moves = levelData["totalMoves"].toInt();
	setTutorial(levelData["tutorial"].toInt()); // will return 0 if no tutorial field

	int functionCount = 3;
	if (levelData.contains("numFunctions"))
		functionCount = levelData["numFunctions"].toInt();
	if (functionCount < 0) functionCount = 0;
	if (functionCount > 3) functionCount = 3; // FIXME: Hide function buttons if not allowed.

	QVariantList functionLimits = levelData["functionLimit"].toList();
	for (int i=0; i<functionCount; i++) {
		Function *f;
		if (i < functionLimits.count())
			f = new Function(functionLimits[i].toInt());
		else
			f = new Function();
		m_functions.append(f);
		qDebug("Function %d limited to %d\n", i, f->count());
	}
	setFunctionCount(functionCount);
	qDebug("Function count: %d\n", functionCount);

	if (width < 0 || width > MAX_WIDTH || height < 0 || height > MAX_HEIGHT || width * height != mapData.count()) {
		qDebug("Bad level data: %dx%d with %d elements\n", width, height, mapData.count());
		return;
	}

	int *data = new int[width*height];
	for (int i=0; i<width*height; i++) {
		data[i] = mapData[i].toInt();
	}

	m_map = new Map(height, width, endX, endY, data, m_mapArea, this);
	Label *movesLabel = m_gamePage->findChild<Label*>("movesLeft");
	m_robot = new Robot(m_map, moves, movesLabel, startX, startY, endX, endY, Robot::getDirection(direction), this);

	m_functionHeader = static_cast<Container *>(m_gamePage->findChild<Container*>("functionHeader"));
	m_functionActions.clear();
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction1")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction2")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction3")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction4")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction5")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction6")));
	m_functionActions.append(static_cast<Container *>(m_gamePage->findChild<Container*>("functionAction7")));
	qDebug("Function header: %p\n", m_functionHeader);
	qDebug("Function actions size: %d\n", m_functionActions.count());

	QObject::connect(m_robot, SIGNAL(moved(int,int)), this, SLOT(robotMoved(int,int)));
}
开发者ID:jnicholl,项目名称:AIMaze,代码行数:83,代码来源:applicationui.cpp

示例4: setFieldData

bool GmpProtocol::setFieldData(int index, const QVariant &value, 
        FieldAttrib attrib)
{
    bool isOk = false;

    if (attrib != FieldValue)
        goto _exit;

    switch (index)
    {
        case kType:
        {
            uint type = value.toUInt(&isOk);
            if (isOk)
                data.set_type(type);
            break;
        }
        case kRsvdMrtCode:
        {
            uint val = value.toUInt(&isOk);
            if (isOk)
                data.set_rsvd_code(val);
            break;
        }
        case kChecksum:
        {
            uint csum = value.toUInt(&isOk);
            if (isOk)
                data.set_checksum(csum);
            break;
        }
        case kMldMrt:
        {
            uint mrt = value.toUInt(&isOk);
            if (isOk)
                data.set_max_response_time(mrt);
            break;
        }
        case kGroupAddress:
            // XXX: Handled by subclass
            isOk = false;
            break;
        case kRsvd1:
            isOk = false;
            break;
        case kSFlag:
        {
            bool flag = value.toBool();
            data.set_s_flag(flag);
            isOk = true;
            break;
        }
        case kQrv:
        {
            uint qrv = value.toUInt(&isOk);
            if (isOk)
                data.set_qrv(qrv);
            break;
        }
        case kQqic:
        {
            uint qqi = value.toUInt(&isOk);
            if (isOk)
                data.set_qqi(qqi);
            break;
        }
        case kSourceCount:
        {
            uint count = value.toUInt(&isOk);
            if (isOk)
                data.set_source_count(count);
            break;
        }
        case kSources:
            // XXX: Handled by subclass
            isOk = false;
            break;
        case kRsvd2:
            isOk = false;
            break;
        case kGroupRecordCount:
        {
            uint count = value.toUInt(&isOk);
            if (isOk)
                data.set_group_record_count(count);
            break;
        }
        case kGroupRecords:
        {
            QVariantList list = value.toList();

            data.clear_group_records();

            for (int i = 0; i < list.count(); i++)
            {
                QVariantMap grpRec = list.at(i).toMap();
                OstProto::Gmp::GroupRecord *rec = data.add_group_records();
                
                rec->set_type(OstProto::Gmp::GroupRecord::RecordType(
                            grpRec["groupRecordType"].toInt()));
//.........这里部分代码省略.........
开发者ID:anju61188,项目名称:ostinato,代码行数:101,代码来源:gmp.cpp

示例5: main

int main(int argc, char **argv)
{
    enum ExitCode
    {
        /**
         * We start from 2, because QApplicationArgumentParser
         * uses 1.
         */
        QueryFailure = 2,
        StdOutFailure
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatterns"));

    QXmlNamePool namePool;
    PatternistApplicationParser parser(argc, argv, namePool);
    parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries."));
    parser.setApplicationVersion(QLatin1String("0.1"));

    QApplicationArgument param(QLatin1String("param"),
                               QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."),
                               qMetaTypeId<Parameter>());
    param.setMaximumOccurrence(-1);
    parser.addArgument(param);

    const QApplicationArgument noformat(QLatin1String("no-format"),
                                        QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed."));
    parser.addArgument(noformat);

    const QApplicationArgument isURI(QLatin1String("is-uri"),
                                     QXmlPatternistCLI::tr("If specified, all filenames on the command line are interpreted as URIs instead of a local filenames."));
    parser.addArgument(isURI);

    const QApplicationArgument initialTemplateName(QLatin1String("initial-template"),
                                                   QXmlPatternistCLI::tr("The name of the initial template to call as a Clark Name."),
                                                   QVariant::String);
    parser.addArgument(initialTemplateName);

    /* The temporary object is required to compile with g++ 3.3. */
    QApplicationArgument queryURI = QApplicationArgument(QLatin1String("query/stylesheet"),
                                                         QXmlPatternistCLI::tr("A local filename pointing to the query to run. If the name ends with .xsl it's assumed "
                                                                               "to be an XSL-T stylesheet. If it ends with .xq, it's assumed to be an XQuery query. (In "
                                                                               "other cases it's also assumed to be an XQuery query, but that interpretation may "
                                                                               "change in a future release of Qt.)"),
                                                         QVariant::String);
    queryURI.setMinimumOccurrence(1);
    queryURI.setNameless(true);
    parser.addArgument(queryURI);

    QApplicationArgument focus = QApplicationArgument(QLatin1String("focus"),
                                                      QXmlPatternistCLI::tr("The document to use as focus. Mandatory "
                                                                            "in case a stylesheet is used. This option is "
                                                                            "also affected by the is-uris option."),
                                                      QVariant::String);
    focus.setMinimumOccurrence(0);
    focus.setNameless(true);
    parser.addArgument(focus);

    QApplicationArgument output(QLatin1String("output"),
                                QXmlPatternistCLI::tr("A local file to which the output should be written. "
                                                      "The file is overwritten, or if not exist, created. "
                                                      "If absent, stdout is used."),
                                qMetaTypeId<QIODevice *>());
    parser.addArgument(output);

    if(!parser.parse())
        return parser.exitCode();

    /* Get the query URI. */
    const QUrl effectiveURI(finalizeURI(parser, isURI, queryURI));

    QXmlQuery::QueryLanguage lang;

    if(effectiveURI.toString().endsWith(QLatin1String(".xsl")))
         lang = QXmlQuery::XSLT20;
    else
         lang = QXmlQuery::XQuery10;

    if(lang == QXmlQuery::XQuery10 && parser.has(initialTemplateName))
    {
        parser.message(QXmlPatternistCLI::tr("An initial template name cannot be specified when running an XQuery."));
        return QApplicationArgumentParser::ParseError;
    }

    QXmlQuery query(lang, namePool);

    query.setInitialTemplateName(qvariant_cast<QXmlName>(parser.value(initialTemplateName)));

    /* Bind external variables. */
    {
        const QVariantList parameters(parser.values(param));
        const int len = parameters.count();

        /* For tracking duplicates. */
        QSet<QString> usedParameters;

        for(int i = 0; i < len; ++i)
        {
            const Parameter p(qvariant_cast<Parameter>(parameters.at(i)));
//.........这里部分代码省略.........
开发者ID:stephaneAG,项目名称:PengPod700,代码行数:101,代码来源:main.cpp

示例6: setFieldData

bool IgmpProtocol::setFieldData(int index, const QVariant &value, 
        FieldAttrib attrib)
{
    bool isOk = false;

    if (attrib != FieldValue)
        goto _exit;

    switch (index)
    {
        case kRsvdMrtCode:
        {
            uint mrt = value.toUInt(&isOk);
            if (isOk)
                data.set_max_response_time(mrt);
            break;
        }
        case kGroupAddress:
        {
            QHostAddress addr(value.toString());
            quint32 ip = addr.toIPv4Address();
            isOk = (addr.protocol() == QAbstractSocket::IPv4Protocol);
            if (isOk)
                data.mutable_group_address()->set_v4(ip);
            break;
        }
        case kSources:
        {
            QStringList list = value.toStringList();

            data.clear_sources();
            foreach(QString str, list)
            {
                quint32 ip = QHostAddress(str).toIPv4Address();
                data.add_sources()->set_v4(ip);
            }
            break;
        }

        case kGroupRecords:
        {
            GmpProtocol::setFieldData(index, value, attrib);
            QVariantList list = value.toList();

            for (int i = 0; i < list.count(); i++)
            {
                QVariantMap grpRec = list.at(i).toMap();
                OstProto::Gmp::GroupRecord *rec = data.mutable_group_records(i);
                
                rec->mutable_group_address()->set_v4(QHostAddress(
                            grpRec["groupRecordAddress"].toString())
                            .toIPv4Address());

                QStringList srcList = grpRec["groupRecordSourceList"]
                                            .toStringList();
                rec->clear_sources();
                foreach (QString src, srcList)
                {
                    rec->add_sources()->set_v4(
                            QHostAddress(src).toIPv4Address());
                }
            }

            break;
        }
开发者ID:Raman325,项目名称:ostinato,代码行数:65,代码来源:igmp.cpp

示例7: call

QVariantList RZQLua::call(std::string const &function_name, QVariantList const &args)
{
    auto const &L = m_lua;

    lua_getglobal(L, function_name.c_str());
    assert(lua_isfunction(L, -1));

    if (args.size() != 0)
    {
        for(auto const &arg : args)
        {
            auto type = arg.type();
            switch (type)
            {
            case QVariant::Type::String:
                lua_pushstring(L, arg.toString().toStdString().c_str());
                break;
            case QVariant::Type::Int:
                lua_pushinteger(L, arg.toInt());
                break;
            case QVariant::Type::Bool:
                lua_pushboolean(L, arg.toInt());
                break;
            case QVariant::Type::Double:
                lua_pushnumber(L, arg.toDouble());
                break;
            default:
                LOG_WARNING("unhandled argument type: " << arg.typeName());
                assert(false);
                break;
            }
        }
    }

    auto top = lua_gettop(L) - args.count();
    lua_pcall(L, args.size(), LUA_MULTRET, 0);
    auto num_rv = lua_gettop(L) - top + 1;

    QVariantList rv;

    for (int i = num_rv - 1; i >= 0; --i)
    {
        int idx = -1 - i;
        auto type = lua_type(L, idx);

        switch (type)
        {
        case LUA_TNUMBER:
            rv.append(lua_tonumber(L, idx));
            break;
        case LUA_TBOOLEAN:
            rv.append(lua_toboolean(L, idx));
            break;
        case LUA_TSTRING:
            rv.append(lua_tostring(L, idx));
            break;
        default:
            LOG_WARNING("unhandled return type: " << lua_typename(L, idx));
            assert(false);
            break;
        }
    }

    lua_pop(L, num_rv);

    return rv;
}
开发者ID:rozetti,项目名称:RZQLua,代码行数:67,代码来源:RZQLua.cpp

示例8: append

void ArrayDataModel::append(const QVariantList &values)
{
    beginInsertRows(QModelIndex(),0, values.count());
    mDatas.prepend(values);
    endInsertRows();
}
开发者ID:dridk,项目名称:ArrayDataModel,代码行数:6,代码来源:arraydatamodel.cpp

示例9: setParameters

void myOperationCustom::setParameters(QVariantList parameters) {
    REQUIRE(parameters.count() != 0);
    //m_Parameter = parameters.at(0).toDouble();

}
开发者ID:INSIGNEO,项目名称:MAF3Tools,代码行数:5,代码来源:myOperationCustomTemplate.cpp

示例10: getData

Client::DataList Client::getData(const string& query) {
    QJsonDocument root;

    QString temp = QString::fromStdString(query);
    QByteArray bytearray = query.c_str();
    QString query_string = QString::fromUtf8(bytearray.data(), bytearray.size());

    qDebug() << "query_string: " << query_string;

    QString uri = getQueryString(query_string);
    qDebug() << "uri: "  << uri;
    get(uri, root);

    DataList result;

    QVariantMap variant = root.toVariant().toMap();

    // Iterate through the weather data
    for (const QVariant &i : variant["businesses"].toList()) {
        QVariantMap item = i.toMap();

        QString name = removeTestInfo(item["name"].toString());
        qDebug() << "name: " << name;

        QString business_url = item["business_url"].toString();
        qDebug() << "business_url: " << business_url;

        QString s_photo_url = item["s_photo_url"].toString();
        qDebug() << "s_photo_url: " << s_photo_url;

        QString photo_url = item["photo_url"].toString();
        qDebug() << "photo_url: " << photo_url;

        QString rating_s_img_url = item["rating_s_img_url"].toString();
        qDebug() << "rating_s_img_url: " << rating_s_img_url;

        QString address = item["address"].toString();
        qDebug() << "address: " << address;

        QString telephone = item["telephone"].toString();
        qDebug() << "telephone: " << telephone;

        QVariantList deals = item["deals"].toList();

        QString summary;
        if ( deals.count() > 0 ) {
            QVariantMap temp = deals.first().toMap();
            summary = temp["description"].toString();
        }

        qDebug() << "summary: " << summary;

        // Add a result to the weather list
        result.emplace_back(
            Data { name.toStdString(), business_url.toStdString(), s_photo_url.toStdString(),
                   photo_url.toStdString(), rating_s_img_url.toStdString(),
                   address.toStdString(), telephone.toStdString(), summary.toStdString() });
    }

    return result;
}
开发者ID:UbuntuChina,项目名称:dianping_scope,代码行数:61,代码来源:client.cpp

示例11: main

int main(int argc, char **argv)
{
    enum ExitCode
    {
        /**
         * We start from 2, because QApplicationArgumentParser
         * uses 1.
         */
        QueryFailure = 2,
        StdOutFailure
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatterns"));

    PatternistApplicationParser parser(argc, argv);
    parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries."));
    parser.setApplicationVersion(QLatin1String("0.1"));

    /* Is there a better way to do this? Probably not, but if the class becomes public, we probably
     * want a helper function that wraps this hack. */
    const int parameterType = qVariantFromValue(Parameter()).userType();
    const int outputType = qVariantFromValue(static_cast<QIODevice *>(0)).userType();

    QApplicationArgument param(QLatin1String("param"),
                               QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."),
                               parameterType);
    param.setMaximumOccurrence(-1);
    parser.addArgument(param);

    const QApplicationArgument noformat(QLatin1String("no-format"),
                                        QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed."));
    parser.addArgument(noformat);

    const QApplicationArgument isURI(QLatin1String("is-uri"),
                                     QXmlPatternistCLI::tr("If specified, the filename is interpreted as a URI instead of a local filename."));
    parser.addArgument(isURI);

    /* The temporary object is required to compile with g++ 3.3. */
    QApplicationArgument queryURI = QApplicationArgument(QString(), /* Nameless. */
                                                         QXmlPatternistCLI::tr("A local filename pointing to the query to run. "
                                                                               "If the name ends with .xq it's assumed "
                                                                               "to be an XQuery query. (In other cases too, but "
                                                                               "that interpretation may change in a future release of Qt.)"),
                                  QVariant::String);
    queryURI.setMinimumOccurrence(1);
    parser.addArgument(queryURI);

    QApplicationArgument output(QLatin1String("output"),
                                QXmlPatternistCLI::tr("A local file to which the output should be written. The file is overwritten, or if not exist, created. If absent, stdout is used."),
                                outputType);
    parser.addArgument(output);

    if(!parser.parse())
        return parser.exitCode();

    QXmlQuery query;

    /* Bind external variables. */
    {
        const QVariantList parameters(parser.values(param));
        const int len = parameters.count();

        for(int i = 0; i < len; ++i)
        {
            const Parameter p(qVariantValue<Parameter>(parameters.at(i)));
            query.bindVariable(p.first, QXmlItem(p.second));
        }
    }

    /* The final preparations and execute the query. */
    QPatternist::ColoringMessageHandler messageHandler;
    query.setMessageHandler(&messageHandler);

    /* Get the query URI. */
    QUrl userURI;
    {
        const QString stringURI(parser.value(queryURI).toString());

        if(parser.has(isURI))
            userURI = QUrl::fromEncoded(stringURI.toLatin1());
        else
            userURI = QUrl::fromLocalFile(stringURI);
    }
    const QUrl effectiveURI(QUrl::fromLocalFile(QDir::current().absolutePath() + QLatin1Char('/')).resolved(userURI));

    Q_ASSERT_X(userURI.isValid(), Q_FUNC_INFO,
               "QApplicationArgumentParser should promise us this.");

    query.setQuery(effectiveURI);

    QIODevice *const outDevice = qVariantValue<QIODevice *>(parser.value(output));
    Q_ASSERT(outDevice);
    Q_ASSERT(outDevice->isWritable());

    if(query.isValid())
    {
        QAbstractXmlReceiver *receiver = 0;

        if(parser.has(noformat))
//.........这里部分代码省略.........
开发者ID:FilipBE,项目名称:qtextended,代码行数:101,代码来源:main.cpp

示例12: invokeMethodWithVariants

/*
taken from http://delta.affinix.com/2006/08/14/invokemethodwithvariants/
thanks to Justin Karneges once again :)
*/
bool MaiaXmlRpcServerConnection::invokeMethodWithVariants( QObject *obj,
                                                           const QByteArray &method,
                                                           const QVariantList &args,
                                                           QVariant *ret,
                                                           Qt::ConnectionType type )
{
    // QMetaObject::invokeMethod() has a 10 argument maximum
    if( args.count() > 10 ) {
        return false;
    }

    QList<QByteArray> argTypes;
    for( int n = 0; n < args.count(); ++n ) {
        argTypes += args[n].typeName();
    }

    // get return type
    int metatype = 0;
    QByteArray retTypeName = getReturnType(obj->metaObject(), method, argTypes);
    if( !retTypeName.isEmpty() && retTypeName != "QVariant" ) {
        metatype = QMetaType::type(retTypeName.data());
        if( metatype == 0 ) {
            // lookup failed
            return false;
        }
    }

    QGenericArgument arg[10];
    for( int n = 0; n < args.count(); ++n ) {
        arg[n] = QGenericArgument(args[n].typeName(), args[n].constData());
    }

    QGenericReturnArgument retarg;
    QVariant retval;
    if( metatype != 0 && retTypeName != "void" ) {
        retval = QVariant(metatype, (const void *)0);
        retarg = QGenericReturnArgument(retval.typeName(), retval.data());
    }
    else {
        /* QVariant */
        retarg = QGenericReturnArgument("QVariant", &retval);
    }

    if( retTypeName.isEmpty() || retTypeName == "void" ) {
        /* void */
        if( !QMetaObject::invokeMethod(obj, method.data(), type,
                                       arg[0], arg[1], arg[2], arg[3], arg[4],
                                       arg[5], arg[6], arg[7], arg[8], arg[9]) ) {
            return false;
        }
    }
    else {
        if( !QMetaObject::invokeMethod(obj, method.data(), type, retarg,
                                       arg[0], arg[1], arg[2], arg[3], arg[4],
                                       arg[5], arg[6], arg[7], arg[8], arg[9]) ) {
            return false;
        }
    }

    if( retval.isValid() && ret ) {
        *ret = retval;
    }
    return true;

} // bool invokeMethodWithVariants( QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type )
开发者ID:naihil,项目名称:libmaia,代码行数:69,代码来源:maiaXmlRpcServerConnection.cpp

示例13: run

void ReverseGeoLookupThread::run() {
	if (geo_lookup_data.isEmpty())
		return;

	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	QEventLoop loop;
	QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3");
	QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50");
	QTimer timer;

	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

	Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) {
		struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site;

		// first check the findNearbyPlaces API from geonames - that should give us country, state, city
		request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));

		QNetworkReply *reply = rgl->get(request);
		timer.setSingleShot(true);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();

		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant geoNamesObject = obj.value("geonames").toVariant();
			QVariantList geoNames = geoNamesObject.toList();
			if (geoNames.count() > 0) {
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
//.........这里部分代码省略.........
开发者ID:Brainiarc7,项目名称:subsurface,代码行数:101,代码来源:divesitehelpers.cpp

示例14: writeOra

void Core::writeOra(const QString& oraPath, const QSize& canvasSize, const QVariantList layerList) {
    QZipWriter zipWriter(oraPath);
    zipWriter.setCompressionPolicy(QZipWriter::AutoCompress);

    QByteArray xmlByteArray;

    // mimetype file
    xmlByteArray.append("image/openraster");
    zipWriter.addFile("mimetype", xmlByteArray);

    // stack.xml file
    QXmlStreamWriter stream(&xmlByteArray);
    stream.setAutoFormatting(true);

    stream.writeStartDocument();

    stream.writeStartElement("image");
    stream.writeAttribute("w", QString::number(canvasSize.width()));
    stream.writeAttribute("h",QString::number(canvasSize.height()));
    stream.writeStartElement("stack");

    QByteArray ba;
    QBuffer buffer(&ba);

    for (int i = 0; i < layerList.count(); i++) {
        QMap<QString, QVariant> map = layerList.at(i).toMap();
        QString name = map.value("name").toString();
        QString isVisible = map.value("isVisible").toString();
        QString isLock = map.value("isLock").toString();
        QString isSelected = map.value("isSelected").toString();

        buffer.open(QIODevice::WriteOnly);
        QObject* obj = qvariant_cast<QObject*>(map.value("canvasItem"));
        CanvasItem* canvasItem = qobject_cast<CanvasItem*>(obj);
        QPixmap* pixmap = canvasItem->pixmap();
        pixmap->save(&buffer, "PNG");
        buffer.close();

        QString src = "data/" + name + ".png";
        zipWriter.addFile(src, ba);

        // layer
        stream.writeStartElement("layer");
        stream.writeAttribute("name", name);
        stream.writeAttribute("composite-op", "svg:src-over");
        stream.writeAttribute("visibility", isVisible == "true" ? "visible" : "hidden");
        stream.writeAttribute("edit-locked", isLock);
        stream.writeAttribute("selected", isSelected);
        stream.writeAttribute("src", src);
        stream.writeAttribute("x", "0");
        stream.writeAttribute("y", "0");
        stream.writeAttribute("opacity", "1.0");
        stream.writeEndElement(); // layer
    }

    stream.writeEndElement(); // stack
    stream.writeEndElement(); // image
    stream.writeEndDocument(); // document
    zipWriter.addFile("stack.xml", xmlByteArray);

    zipWriter.close();
}
开发者ID:,项目名称:,代码行数:62,代码来源:

示例15: hasChildren

bool ODataListModel::hasChildren(const QVariantList& indexPath) {
    // we aren't multilevel so we are only concerned with the root having children
    return indexPath.count() == 0 && !mDataList.isEmpty();
}
开发者ID:blackberry,项目名称:OData-BB10,代码行数:4,代码来源:ODataListModel.cpp


注:本文中的QVariantList::count方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。