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


C++ QMap类代码示例

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


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

示例1: qDebug

int CreateFunction::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (DEBUG)
    qDebug("CreateFunction::writeToDb(%s, %s, &errMsg)",
           pdata.data(), qPrintable(pkgname));

  QSqlQuery oidq;
  QMap<QString,int> oldoids;

  if (! pkgname.isEmpty())
  {
    oidq.prepare("SELECT pg_proc.oid, oidvectortypes(proargtypes) "
                 "FROM pg_proc, pg_namespace "
                 "WHERE ((pg_namespace.oid=pronamespace)"
                 "  AND  (proname=:name)"
                 "  AND  (nspname=:schema));");
    oidq.bindValue(":name",   _name);
    oidq.bindValue(":schema", pkgname);

    oidq.exec();
    while (oidq.next())
    {
      oldoids.insert(oidq.value(1).toString(), oidq.value(0).toInt());
    }
    if (oidq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(oidq.lastError().databaseText())
                        .arg(oidq.lastError().driverText());
      return -1;
    }
    if (DEBUG)
    {
      QMap<QString, int>::const_iterator i = oldoids.constBegin();
      while (i != oldoids.constEnd())
      {
        qDebug("CreateFunction::writeToDB() %s(%s) -> %d",
               qPrintable(_name), qPrintable(i.key()), i.value());
        i++;
      }
    }
  }

  int returnVal = Script::writeToDB(pdata, pkgname, errMsg);
  if (returnVal < 0)
    return returnVal;

  if (! pkgname.isEmpty())
  {
    QSqlQuery select;
    int pkgheadid = -1;
    select.prepare("SELECT pkghead_id FROM pkghead WHERE (pkghead_name=:name);");
    select.bindValue(":name", pkgname);
    select.exec();
    if (select.first())
      pkgheadid = select.value(0).toInt();
    else if (select.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(select.lastError().databaseText())
                        .arg(select.lastError().driverText());
      return -4;
    }

    oidq.exec();        // reuse the query
    int count = 0;
    while (oidq.next())
    {
      if (DEBUG)
        qDebug("CreateFunction::writeToDB() oid = %d, argtypes = %s",
               oidq.value(0).toInt(), qPrintable(oidq.value(1).toString()));
      int tmp = upsertPkgItem(pkgheadid, oldoids,
                              oidq.value(1).toString(), oidq.value(0).toInt(),
                              errMsg);
      if (tmp < 0)
        return tmp;
      count++;
    }
    if (oidq.lastError().type() != QSqlError::NoError)
    {
      errMsg = _sqlerrtxt.arg(_filename)
                        .arg(oidq.lastError().databaseText())
                        .arg(oidq.lastError().driverText());
      return -5;
    }
    if (count == 0)
    {
      errMsg = TR("Could not find function %1 in the database for package %2. "
                  "The script %3 does not match the contents.xml description.")
                .arg(_name).arg(pkgname).arg(_filename);
      return -6;
    }
  }

  return 0;
}
开发者ID:gpazo,项目名称:xtuple-svn,代码行数:96,代码来源:createfunction.cpp

示例2: LOG_STRM_DEBUG

bool SASLAuthFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder)
{
	if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE)
	{
		if (AStanza.kind() == "challenge")
		{
			QByteArray challengeData = QByteArray::fromBase64(AStanza.element().text().toLatin1());
			LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth challenge received: %1").arg(QString::fromUtf8(challengeData)));
			
			QMap<QByteArray, QByteArray> responseMap;
			QMap<QByteArray, QByteArray> challengeMap = parseChallenge(challengeData);
			if (challengeMap.value("qop") == "auth")
			{
				QByteArray randBytes(32,' ');
				for (int i=0; i<randBytes.size(); i++)
					randBytes[i] = (char) (256.0 * qrand() / (RAND_MAX + 1.0));

				responseMap["cnonce"] = randBytes.toHex();
				if (challengeMap.contains("realm"))
					responseMap["realm"] = challengeMap.value("realm");
				else
					responseMap["realm"] = FXmppStream->streamJid().pDomain().toUtf8();
				responseMap["username"] = FXmppStream->streamJid().pNode().toUtf8();
				responseMap["nonce"] = challengeMap.value("nonce");
				responseMap["nc"] = "00000001";
				responseMap["qop"] = "auth";
				responseMap["digest-uri"] = QString("xmpp/%1").arg(FXmppStream->streamJid().pDomain()).toUtf8();
				responseMap["charset"] = "utf-8";
				responseMap["response"] = getResponseValue(responseMap,FXmppStream->password());
			}
			QByteArray responseData = serializeResponse(responseMap);

			Stanza response("response",NS_FEATURE_SASL);
			response.element().appendChild(response.createTextNode(responseData.toBase64()));
			FXmppStream->sendStanza(response);

			LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth response sent: %1").arg(QString::fromUtf8(responseData)));
		}
		else
		{
			FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this);
			if (AStanza.kind() == "success")
			{
				LOG_STRM_INFO(FXmppStream->streamJid(),"Authorization successes");
				deleteLater();
				emit finished(true);
			}
			else if (AStanza.kind() == "failure")
			{
				XmppSaslError err(AStanza.element());
				LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization failed: %1").arg(err.condition()));
				emit error(err);
			}
			else
			{
				XmppError err(IERR_SASL_AUTH_INVALID_RESPONSE);
				LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization error: Invalid stanza kind=%1").arg(AStanza.kind()));
				emit error(err);
			}
		}
		return true;
	}
	return false;
}
开发者ID:ChALkeR,项目名称:vacuum-im,代码行数:64,代码来源:saslauthfeature.cpp

示例3: k

bool HsMenuClientPrivate::add(const QVariantMap &entryPreference)
{
    bool result = false;
    QMap<QString, QVariant> pref = entryPreference;
    
    CaIconDescription iconDesc;
    if(pref.contains(hsItemId))
        {
            QSharedPointer<CaEntry> update_entry = CaService::instance()->getEntry(pref.take(hsItemId).toInt());
            
            if(pref.contains(hsItemLocName))
                {
                update_entry->setText(pref.take(hsItemLocName).toString(),true);
                }
            else
                {
                update_entry->setText(pref.take(hsItemName).toString());   
                }
            
            if(pref.contains(hsItemLocDescription))
                {
                update_entry->setDescription(pref.take(hsItemLocDescription).toString(), true);
                }
            else
                {
                update_entry->setDescription(pref.take(hsItemDescription).toString());
                }                                             
            
            iconDesc.setFilename(pref.take(hsIconFileName).toString());
            iconDesc.setSkinId(pref.take(hsIconName).toString());
            iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString());
            update_entry->setIconDescription(iconDesc);
            QMapIterator<QString, QVariant> k(pref);
            while (k.hasNext()) {
                k.next();
                update_entry->setAttribute(k.key(),k.value().toString());
            }
            
            result = CaService::instance()->updateEntry(*update_entry);
        }
    else if ((pref.contains(hsItemName) || pref.contains(hsItemLocName)) && pref.contains(hsitemLaunchUri) && pref.contains(hsitemPublisherId))
        {
            CaEntry add_entry(ItemEntryRole);
            add_entry.setEntryTypeName(Hs::templatedApplicationTypeName);
            // mandatory values
            if(pref.contains(hsItemLocName))
                {
                add_entry.setText(pref.take(hsItemLocName).toString(),true);
                }
            else
                {
                add_entry.setText(pref.take(hsItemName).toString());
                }
            
            iconDesc.setFilename(pref.take(hsIconFileName).toString());
            iconDesc.setSkinId(pref.take(hsIconName).toString());
            iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString());            
            add_entry.setIconDescription(iconDesc);  
            
            if(pref.contains(hsItemLocDescription))
                {
                add_entry.setDescription(pref.take(hsItemLocDescription).toString(), true);
                }
            else
                {
                add_entry.setDescription(pref.take(hsItemDescription).toString());
                }  
            QMapIterator<QString, QVariant> k(pref);
            while (k.hasNext()) {
                k.next();
                add_entry.setAttribute(k.key(),k.value().toString());
            }

            add_entry.setFlags(add_entry.flags() & ~RemovableEntryFlag);
            
            QSharedPointer<CaEntry> entry = CaService::instance()->createEntry(add_entry);
            if (!entry.isNull()) {
                result = true;
            }      
        }
    else
        {
            return false;
        }
    return result;
    
  
}
开发者ID:cdaffara,项目名称:symbiandump-ossapps,代码行数:88,代码来源:hsmenuclient.cpp

示例4: AXRError

bool XMLParser::loadFile(QSharedPointer<AXRBuffer> file)
{
    if (!d->controller)
    {
        throw AXRError("XMLParser", "The controller was not set on the XML parser");
    }

    axr_log(LoggerChannelOverview, "XMLParser: loading file " + file->sourceUrl().toString());

    if (!file->isValid())
    {
        axr_log(LoggerChannelOverview, "XMLParser: failed to load file " + file->sourceUrl().toString());
        return false;
    }

    try
    {
        // Parse the XML file...
        QXmlStreamReader xml(file->getBuffer());
        while (!xml.atEnd() && !xml.hasError())
        {
            xml.readNext();
            if (xml.isStartElement())
            {
                AXRString name = xml.name().toString();
                axr_log(LoggerChannelXMLParser, "XMLParser: found opening tag with name " + name);
                d->controller->enterElement(name);

                Q_FOREACH (const QXmlStreamAttribute &attr, xml.attributes())
                {
                    d->controller->addAttribute(attr.name().toString(), attr.value().toString());
                }
            }
            else if (xml.isEndElement())
            {
                axr_log(LoggerChannelXMLParser, "XMLParser: found closing tag with name " + xml.name().toString());
                d->controller->exitElement();
            }
            else if (xml.isCharacters())
            {
                axr_log(LoggerChannelXMLParser, AXRString("XMLParser: reading character data: \"%1\"").arg(xml.text().toString()));
                d->controller->appendContentText(xml.text().toString());
            }
            else if (xml.isProcessingInstruction())
            {
                AXRString instructionName = xml.processingInstructionTarget().toString();
                axr_log(LoggerChannelXMLParser, "XMLParser: found XML instruction with name " + instructionName);

                // Probable HSS stylesheet encountered, try to load it into the controller
                if (instructionName == "xml-stylesheet")
                {
                    QMap<AXRString, AXRString> instructionAttributes;

                    // A little trickery to easily parse the key-value pairs from the instruction...
                    // We basically embed the processing instruction value, which looks like a set of XML
                    // attributes, within a fake XML tag to create a document that we can parse, allowing
                    // the XML parser to handle the syntax instead of doing it manually
                    QXmlStreamReader instructionParser(AXRString("<node %1 />").arg(xml.processingInstructionData().toString()));
                    while (!instructionParser.atEnd() && !instructionParser.hasError())
                    {
                        instructionParser.readNext();
                        if (instructionParser.isStartElement())
                        {
                            // Read all the attributes from our fake tag, which are the xml-stylesheet parameters
                            Q_FOREACH (const QXmlStreamAttribute &attr, instructionParser.attributes())
                            {
                                instructionAttributes.insert(attr.name().toString(), attr.value().toString());
                            }
                        }
                    }
开发者ID:axr,项目名称:core,代码行数:70,代码来源:XMLParser.cpp

示例5: getParentClassifier

// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we resonablely will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void DClassifierCodeDocument::updateContent()
{
    // Gather info on the various fields and parent objects of this class...
    UMLClassifier * c = getParentClassifier();
    Q_ASSERT(c != 0);
    CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy();
    CodeGenPolicyExt * pe = UMLApp::app()->policyExt();
    DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe);

    // first, set the global flag on whether or not to show classfield info
    // This depends on whether or not we have attribute/association classes
    const CodeClassFieldList * cfList = getCodeClassFieldList();
    CodeClassFieldList::const_iterator it = cfList->begin();
    CodeClassFieldList::const_iterator end = cfList->end();
    for (; it != end; ++it) {
        CodeClassField * field = *it;
        if (field->parentIsAttribute())
            field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors());
        else
            field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors());
    }

    // attribute-based ClassFields
    // we do it this way to have the static fields sorted out from regular ones
    CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true);
    CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false);
    // association-based ClassFields
    // don't care if they are static or not..all are lumped together
    CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation);
    CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation);
    CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition);

    bool isInterface = parentIsInterface();
    bool hasOperationMethods = false;

    UMLOperationList list = c->getOpList();
    hasOperationMethods = ! list.isEmpty();

    QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time

    //
    // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
    //

    //
    // PACKAGE CODE BLOCK
    //
    QString pkgs = getPackage();
    pkgs.replace(QRegExp(QLatin1String("::")), QLatin1String("."));
    QString packageText = getPackage().isEmpty() ? QString() : QString(QLatin1String("package ")+pkgs+QLatin1Char(';')+endLine);
    CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("packages"), packageText, QString(), 0, false);
    if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated)
        pblock->setWriteOutText(false);
    else
        pblock->setWriteOutText(true);

    // IMPORT CODEBLOCK
    //
    // Q: Why all utils? Aren't just List and Vector the only classes we are using?
    // A: doesn't matter at all; it is more readable to just include '*' and d compilers
    //    don't slow down or anything. (TZ)
    QString importStatement;
    if (hasObjectVectorClassFields())
        importStatement.append(QLatin1String("import d.util.*;"));

    //only import classes in a different package from this class
    UMLPackageList imports;
    QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages

    CodeGenerator::findObjectsRelated(c, imports);
    for (UMLPackageListIt importsIt(imports); importsIt.hasNext();) {
        UMLPackage *con = importsIt.next();
        // NO (default) datatypes in the import statement.. use defined
        // ones whould be possible, but no idea how to do that...at least for now.
        // Dynamic casting is slow..not an optimal way to do this.
        if (!packageMap.contains(con) && !con->isUMLDatatype())
        {
            packageMap.insert(con, con->package());

            // now, we DON'T need to import classes that are already in our own package
            // (that is, IF a package is specified). Otherwise, we should have a declaration.
            if (con->package() != c->package() ||
                    (c->package().isEmpty() && con->package().isEmpty()))
            {
                importStatement.append(endLine+QLatin1String("import "));
                if (!con->package().isEmpty())
                    importStatement.append(con->package()+QLatin1Char('.'));
                importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';'));
            }
        }
    }
    // now, add/update the imports codeblock
    CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("imports"), importStatement, QString(), 0, false);
//.........这里部分代码省略.........
开发者ID:KDE,项目名称:umbrello,代码行数:101,代码来源:dclassifiercodedocument.cpp

示例6: QLabel

QList<QPair<QLabel*, QWidget*> > QgsVectorLayerSaveAsDialog::createControls( const QMap<QString, QgsVectorFileWriter::Option*>& options )
{
  QList<QPair<QLabel*, QWidget*> > controls;
  QMap<QString, QgsVectorFileWriter::Option*>::ConstIterator it;

  for ( it = options.constBegin(); it != options.constEnd(); ++it )
  {
    QgsVectorFileWriter::Option* option = it.value();
    QLabel* label = new QLabel( it.key() );
    QWidget* control;
    switch ( option->type )
    {
      case QgsVectorFileWriter::Int:
      {
        QgsVectorFileWriter::IntOption* opt = dynamic_cast<QgsVectorFileWriter::IntOption*>( option );
        QSpinBox* sb = new QSpinBox();
        sb->setObjectName( it.key() );
        sb->setValue( opt->defaultValue );
        control = sb;
        break;
      }

      case QgsVectorFileWriter::Set:
      {
        QgsVectorFileWriter::SetOption* opt = dynamic_cast<QgsVectorFileWriter::SetOption*>( option );
        QComboBox* cb = new QComboBox();
        cb->setObjectName( it.key() );
        Q_FOREACH( const QString& val, opt->values )
        {
          cb->addItem( val, val );
        }
        if ( opt->allowNone )
          cb->addItem( tr( "<Default>" ), QVariant( QVariant::String ) );
        int idx = cb->findText( opt->defaultValue );
        if ( idx == -1 )
          idx = cb->findData( QVariant( QVariant::String ) );
        cb->setCurrentIndex( idx );
        control = cb;
        break;
      }

      case QgsVectorFileWriter::String:
      {
        QgsVectorFileWriter::StringOption* opt = dynamic_cast<QgsVectorFileWriter::StringOption*>( option );
        QLineEdit* le = new QLineEdit( opt->defaultValue );
        le->setObjectName( it.key() );
        control = le;
        break;
      }

      case QgsVectorFileWriter::Hidden:
        control = 0;
        break;
    }

    if ( control )
    {
      // Pack the tooltip in some html element, so it gets linebreaks.
      label->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) );
      control->setToolTip( QString( "<p>%1</p>" ).arg( option->docString ) );

      controls << QPair<QLabel*, QWidget*>( label, control );
    }
  }

  return controls;
}
开发者ID:DoctorGana,项目名称:QGIS,代码行数:67,代码来源:qgsvectorlayersaveasdialog.cpp

示例7: GetOperationInfo_sys

void GetSystemDetails::GetOperationInfo_sys(QMap<QString, QMap<QString, QStringList> > &OutData)
{

	if(mdllPath.compare("") ==0)
	{
		QMessageBox::warning(NULL,"exit",mdllPath);
		return;
	}
    qDebug() << "Load Operation is start" << mdllPath;
    sysDllLibrary = new QLibrary(mdllPath);
    if ( sysDllLibrary->load() ){


        typedef BOOL (*GetFunction)(INFOLIST**);
        GetFunction GetOperationDetails = (GetFunction) sysDllLibrary->resolve("GetOperationDetails");

        typedef void (*FreeFunction)(INFOLIST*);
        FreeFunction FreeOperListBuff = (FreeFunction) sysDllLibrary->resolve("FreeOperListBuff");


        QString namePara;
        namePara = "Operating System";

        INFOLIST* rListData = NULL;
        GetOperationDetails(&rListData);
       
		qDebug() << "Get result Data!" << rListData->m_Count;

        ////Get return result Data
        mDetails.clear();
        QString ItemName;
        QString ItemValue;
        cDetailsMap.clear();

        for (int i=0; i<rListData->m_Count; i++){
            ItemName.clear();
            ItemValue.clear();

            qDebug() << "Data: " << QString::fromWCharArray(rListData->lpItem[i].m_Name)
                     << "-->" << QString::fromWCharArray(rListData->lpItem[i].m_Value);

            ItemName = QString::fromWCharArray(rListData->lpItem[i].m_Name);
            ItemValue = QString::fromWCharArray(rListData->lpItem[i].m_Value);

            mDetails.push_back(ItemName);
            mDetails.push_back(ItemValue);

        }

        cDetailsMap.insert("OpertionInfo", mDetails);
        OutData.insert(namePara, cDetailsMap);


        //ÊÍ·ÅÄÚ´æ
        FreeOperListBuff(rListData);
        sysDllLibrary->unload();

    }else {
        qDebug() << "Load " << mdllPath << " is failed";

        mDetails.clear();
        mDetails.push_back("Load the ComputerDetails.dll is failed");
        cDetailsMap.clear();
        cDetailsMap.insert("Failed", mDetails);
        OutData.insert("Load Error", cDetailsMap);
        cDetailsMap.clear();
    }


}
开发者ID:daddyreb,项目名称:Bigit_Genie,代码行数:70,代码来源:getsystemdetails.cpp

示例8: currentLayer

QFont QgsMapToolLabel::labelFontCurrentFeature()
{
  QFont font;
  QgsVectorLayer* vlayer = currentLayer();

  bool labelSettingsOk;
  QgsPalLayerSettings& layerSettings = currentLabelSettings( &labelSettingsOk );

  if ( labelSettingsOk && vlayer )
  {
    font = layerSettings.textFont;

    QgsFeature f;
    if ( vlayer->featureAtId( mCurrentLabelPos.featureId, f, false, true ) )
    {
      const QgsAttributeMap& attributes = f.attributeMap();
      QMap< QgsPalLayerSettings::DataDefinedProperties, int > ddProperties = layerSettings.dataDefinedProperties;

      //size
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator sizeIt = ddProperties.find( QgsPalLayerSettings::Size );
      if ( sizeIt != ddProperties.constEnd() )
      {
        if ( layerSettings.fontSizeInMapUnits )
        {
          font.setPixelSize( layerSettings.sizeToPixel( attributes[*sizeIt].toDouble(), QgsRenderContext() ) );
        }
        else
        {
          font.setPointSizeF( attributes[*sizeIt].toDouble() );
        }
      }

      //family
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator familyIt = ddProperties.find( QgsPalLayerSettings::Family );
      if ( familyIt != ddProperties.constEnd() )
      {
        font.setFamily( attributes[*sizeIt].toString() );
      }

      //underline
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator underlineIt = ddProperties.find( QgsPalLayerSettings::Underline );
      if ( familyIt != ddProperties.constEnd() )
      {
        font.setUnderline( attributes[*underlineIt].toBool() );
      }

      //strikeout
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator strikeoutIt = ddProperties.find( QgsPalLayerSettings::Strikeout );
      if ( strikeoutIt != ddProperties.constEnd() )
      {
        font.setStrikeOut( attributes[*strikeoutIt].toBool() );
      }

      //bold
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator boldIt = ddProperties.find( QgsPalLayerSettings::Bold );
      if ( boldIt != ddProperties.constEnd() )
      {
        font.setBold( attributes[*boldIt].toBool() );
      }

      //italic
      QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator italicIt = ddProperties.find( QgsPalLayerSettings::Italic );
      if ( italicIt != ddProperties.constEnd() )
      {
        font.setItalic( attributes[*italicIt].toBool() );
      }
    }
  }

  return font;
}
开发者ID:namhh,项目名称:Quantum-GIS,代码行数:71,代码来源:qgsmaptoollabel.cpp

示例9: rx

LuaSkillCard *LuaSkillCard::Parse(const QString &str) {
    QRegExp rx("#(\\w+):(.*):(.*)");
    QRegExp e_rx("#(\\w*)\\[(\\w+):(.+)\\]:(.*):(.*)");

    static QMap<QString, Card::Suit> suit_map;
    if (suit_map.isEmpty()) {
        suit_map.insert("spade", Card::Spade);
        suit_map.insert("club", Card::Club);
        suit_map.insert("heart", Card::Heart);
        suit_map.insert("diamond", Card::Diamond);
        suit_map.insert("no_suit_red", Card::NoSuitRed);
        suit_map.insert("no_suit_black", Card::NoSuitBlack);
        suit_map.insert("no_suit", Card::NoSuit);
    }

    QStringList texts;
    QString name, suit, number;
    QString subcard_str;
    QString user_string;

    if (rx.exactMatch(str)) {
        texts = rx.capturedTexts();
        name = texts.at(1);
        subcard_str = texts.at(2);
        user_string = texts.at(3);
    } else if (e_rx.exactMatch(str)) {
        texts = e_rx.capturedTexts();
        name = texts.at(1);
        suit = texts.at(2);
        number = texts.at(3);
        subcard_str = texts.at(4);
        user_string = texts.at(5);
    } else
        return NULL;

    const LuaSkillCard *c = LuaSkillCards.value(name, NULL);
    if (c == NULL)
        return NULL;

    LuaSkillCard *new_card = c->clone();

    if (subcard_str != ".")
        new_card->addSubcards(StringList2IntList(subcard_str.split("+")));

    if (!suit.isEmpty())
        new_card->setSuit(suit_map.value(suit, Card::NoSuit));
    if (!number.isEmpty()) {
        int num = 0;
        if (number == "A")
            num = 1;
        else if (number == "J")
            num = 11;
        else if (number == "Q")
            num = 12;
        else if (number == "K")
            num = 13;
        else
            num = number.toInt();

        new_card->setNumber(num);
    }

    new_card->setUserString(user_string);
    QString skillName = LuaSkillCardsSkillName.value(name, QString());
    if (skillName.isEmpty())
        skillName = name.toLower().remove("card");
    new_card->setSkillName(skillName);
    return new_card;
}
开发者ID:vuuvv,项目名称:QSanguosha,代码行数:69,代码来源:lua-wrapper.cpp

示例10: main

int main(int argc, char *argv[])
{
  QMap<QString,ParamPair> paramList;
  QString username  = "";
  QString filename;
  QString printerName;
  bool    haveUsername    = FALSE;
  bool    haveDatabaseURL = FALSE;
  bool    loggedIn        = FALSE;
  bool    print           = FALSE;
  bool    printPreview    = FALSE;
  bool    close           = FALSE;
  int     numCopies       = 1;
  // BVI::Sednacom
  // new options
  bool    pdfOutput = FALSE;
  QString pdfFileName;
  // BVI::Sednacom

  QString databaseURL = "";
  QString loadFromDB = "";

  QApplication app(argc, argv);
  app.addLibraryPath(".");

  OpenRPT::languages.addTranslationToDefault(":/common.qm");
  OpenRPT::languages.addTranslationToDefault(":/wrtembed.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderer.qm");
  OpenRPT::languages.addTranslationToDefault(":/renderapp.qm");
  OpenRPT::languages.installSelected();

  if (app.argc() > 1)
  {
    haveUsername        = FALSE;
    bool    havePasswd          = FALSE;
    QString passwd              = "";

    QStringList arguments;
    QString firstArgument = QString( app.argv()[ 1 ] );

    if( firstArgument.startsWith("-fromStdin=", Qt::CaseInsensitive) ){
      QFile file;
      file.open(stdin, QIODevice::ReadOnly);
      QTextStream in(&file);
      in.setCodec( firstArgument.right( firstArgument.length() - 11 ).toAscii() ); 
      QString arg;
      while( arg.compare("-launch") !=0 ){
        arg = in.readLine();
        arguments << arg;
      }
      file.close();
    }
    else{
      for (int intCounter = 1; intCounter < app.argc(); intCounter++){
        arguments << QString (app.argv()[intCounter]);
      }
    }

    for ( QStringList::Iterator it = arguments.begin(); it != arguments.end(); ++it ) {
      QString argument( *it );

      if (argument.startsWith("-databaseURL=", Qt::CaseInsensitive)) {
        haveDatabaseURL = TRUE;
        databaseURL    = argument.right(argument.length() - 13);
      }
      else if (argument.startsWith("-username=", Qt::CaseInsensitive))
      {
        haveUsername = TRUE;
        username     = argument.right(argument.length() - 10);
      }
      else if (argument.startsWith("-passwd=", Qt::CaseInsensitive))
      {
        havePasswd = TRUE;
        passwd     = argument.right(argument.length() - 8);
      }
      else if (argument.toLower() == "-noauth")
      {
        haveUsername = TRUE;
        havePasswd   = TRUE;
      }
      else if (argument.startsWith("-numCopies=", Qt::CaseInsensitive)){
        numCopies = argument.right( argument.length() - 11).toInt();
      }
      else if (argument.toLower() == "-print")
        print = true;
      else if (argument.toLower() == "-printpreview")
        printPreview = true;
      else if (argument.toLower() == "-close")
        close = true;
      else if (argument.startsWith("-printerName=", Qt::CaseInsensitive))
        printerName = argument.right(argument.length() - 13);
      else if (argument.startsWith("-param=", Qt::CaseInsensitive))
      {
        QString str = argument.right(argument.length() - 7);
        bool active = true;
        QString name;
        QString type;
        QString value;
        QVariant var;
        int sep = str.indexOf('=');
//.........这里部分代码省略.........
开发者ID:Wushaowei001,项目名称:xtuple,代码行数:101,代码来源:main.cpp

示例11: processCalculation

int QgsRasterCalculator::processCalculation( QProgressDialog* p )
{
  //prepare search string / tree
  QString errorString;
  QgsRasterCalcNode* calcNode = QgsRasterCalcNode::parseRasterCalcString( mFormulaString, errorString );
  if ( !calcNode )
  {
    //error
    return static_cast<int>( ParserError );
  }

  QMap< QString, QgsRasterBlock* > inputBlocks;
  QVector<QgsRasterCalculatorEntry>::const_iterator it = mRasterEntries.constBegin();
  for ( ; it != mRasterEntries.constEnd(); ++it )
  {
    if ( !it->raster ) // no raster layer in entry
    {
      delete calcNode;
      qDeleteAll( inputBlocks );
      return static_cast< int >( InputLayerError );
    }

    QgsRasterBlock* block = nullptr;
    // if crs transform needed
    if ( it->raster->crs() != mOutputCrs )
    {
      QgsRasterProjector proj;
      proj.setCrs( it->raster->crs(), mOutputCrs );
      proj.setInput( it->raster->dataProvider() );
      proj.setPrecision( QgsRasterProjector::Exact );

      block = proj.block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows );
    }
    else
    {
      block = it->raster->dataProvider()->block( it->bandNumber, mOutputRectangle, mNumOutputColumns, mNumOutputRows );
    }
    if ( block->isEmpty() )
    {
      delete block;
      delete calcNode;
      qDeleteAll( inputBlocks );
      return static_cast<int>( MemoryError );
    }
    inputBlocks.insert( it->ref, block );
  }

  //open output dataset for writing
  GDALDriverH outputDriver = openOutputDriver();
  if ( !outputDriver )
  {
    return static_cast< int >( CreateOutputError );
  }

  GDALDatasetH outputDataset = openOutputFile( outputDriver );
  GDALSetProjection( outputDataset, mOutputCrs.toWkt().toLocal8Bit().data() );
  GDALRasterBandH outputRasterBand = GDALGetRasterBand( outputDataset, 1 );

  float outputNodataValue = -FLT_MAX;
  GDALSetRasterNoDataValue( outputRasterBand, outputNodataValue );

  if ( p )
  {
    p->setMaximum( mNumOutputRows );
  }

  QgsRasterMatrix resultMatrix;
  resultMatrix.setNodataValue( outputNodataValue );

  //read / write line by line
  for ( int i = 0; i < mNumOutputRows; ++i )
  {
    if ( p )
    {
      p->setValue( i );
    }

    if ( p && p->wasCanceled() )
    {
      break;
    }

    if ( calcNode->calculate( inputBlocks, resultMatrix, i ) )
    {
      bool resultIsNumber = resultMatrix.isNumber();
      float* calcData = new float[mNumOutputColumns];

      for ( int j = 0; j < mNumOutputColumns; ++j )
      {
        calcData[j] = ( float )( resultIsNumber ? resultMatrix.number() : resultMatrix.data()[j] );
      }

      //write scanline to the dataset
      if ( GDALRasterIO( outputRasterBand, GF_Write, 0, i, mNumOutputColumns, 1, calcData, mNumOutputColumns, 1, GDT_Float32, 0, 0 ) != CE_None )
      {
        QgsDebugMsg( "RasterIO error!" );
      }

      delete[] calcData;
    }
//.........这里部分代码省略.........
开发者ID:Gustry,项目名称:QGIS,代码行数:101,代码来源:qgsrastercalculator.cpp

示例12: menu

void LibraryTreeWidget::onCustomContextMenuRequested(const QPoint& pos)
{
	QMenu menu(this);

	bool file = false;
	bool folder = false;
	bool project = false;

	int size = selectedItems().size();

	for (int i = 0; i < selectedItems().size(); ++i)
	{
		if (selectedItems()[i]->parent() == NULL)
		{
			project = true;
		}
		else
		{
			QString fileName = selectedItems()[i]->data(0, Qt::UserRole).toMap()["filename"].toString();

			if (fileName.isEmpty() == true)
				folder = true;
			else
				file = true;
		}
	}

	if (size == 1 && (folder || project))
	{
		menu.addAction(addNewFileAction_);
		menu.addAction(importToLibraryAction_);
		menu.addAction(newFolderAction_);
	}

	if (size > 0 && !project)
		menu.addAction(removeAction_);
	if (size == 1 && folder)
		menu.addAction(renameAction_);
	if (size == 1 && (folder || project))
		menu.addAction(sortAction_);

	if (size == 1 && file)
	{
		menu.addAction(insertIntoDocumentAction_);

		QMap<QString, QVariant> data = selectedItems()[0]->data(0, Qt::UserRole).toMap();

		QString fileName = data["filename"].toString();

		QFileInfo fileInfo(fileName);

		QString ext = fileInfo.suffix().toLower();

		if (ext == "lua")
        {
            menu.addAction(codeDependenciesAction_);
            bool excludeFromExecution = data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool();
            excludeFromExecutionAction_->setChecked(excludeFromExecution);
            menu.addAction(excludeFromExecutionAction_);
        }

		if (ext == "png" || ext == "jpg" || ext == "jpeg")
		{
			bool downsizing = data.contains("downsizing") && data["downsizing"].toBool();
			automaticDownsizingAction_->setChecked(downsizing);
			menu.addAction(automaticDownsizingAction_);
		}
	}

	if (size == 1 && project)
		menu.addAction(projectPropertiesAction_);

	if (!menu.isEmpty())
		menu.exec(QCursor::pos());
}
开发者ID:dev-life,项目名称:gideros,代码行数:75,代码来源:librarytreewidget.cpp

示例13: invisibleRootItem

QDomDocument LibraryTreeWidget::toXml() const
{
	QDomDocument doc;
	QDomElement root = doc.createElement("project");

	QDomElement properties = doc.createElement("properties");

	// graphics options
	properties.setAttribute("scaleMode", properties_.scaleMode);
	properties.setAttribute("logicalWidth", properties_.logicalWidth);
	properties.setAttribute("logicalHeight", properties_.logicalHeight);
	QDomElement imageScales = doc.createElement("imageScales");
	for (size_t i = 0; i < properties_.imageScales.size(); ++i)
	{
		QDomElement scale = doc.createElement("scale");

		scale.setAttribute("suffix", properties_.imageScales[i].first);
		scale.setAttribute("scale", properties_.imageScales[i].second);

		imageScales.appendChild(scale);
	}
	properties.appendChild(imageScales);
	properties.setAttribute("orientation", properties_.orientation);
	properties.setAttribute("fps", properties_.fps);

	// iOS options
    properties.setAttribute("retinaDisplay", properties_.retinaDisplay);
	properties.setAttribute("autorotation", properties_.autorotation);

    // input options
    properties.setAttribute("mouseToTouch", properties_.mouseToTouch ? 1 : 0);
    properties.setAttribute("touchToMouse", properties_.touchToMouse ? 1 : 0);
    properties.setAttribute("mouseTouchOrder", properties_.mouseTouchOrder);

	// export options
	properties.setAttribute("architecture", properties_.architecture);
	properties.setAttribute("assetsOnly", properties_.assetsOnly ? 1 : 0);
	properties.setAttribute("iosDevice", properties_.iosDevice);
	properties.setAttribute("packageName", properties_.packageName);
    properties.setAttribute("encryptCode", properties_.encryptCode);
    properties.setAttribute("encryptAssets", properties_.encryptAssets);


	root.appendChild(properties);

	doc.appendChild(root);

	QTreeWidgetItem* rootitem = invisibleRootItem();
	if (rootitem->childCount())
		rootitem = rootitem->child(0);

	std::stack<std::pair<QTreeWidgetItem*, QDomElement> > stack;
	stack.push(std::make_pair(rootitem, root));

	while (stack.empty() == false)
	{
		QTreeWidgetItem* item = stack.top().first;
		QDomElement element = stack.top().second;
		stack.pop();

		for (int i = 0; i < item->childCount(); ++i)
		{
			QTreeWidgetItem* childItem = item->child(i);

			QMap<QString, QVariant> data = childItem->data(0, Qt::UserRole).toMap();
			QString fileName = data["filename"].toString();

			QDomElement childElement = doc.createElement(fileName.isEmpty() ? "folder" : "file");
			if (fileName.isEmpty() == false)
			{
				childElement.setAttribute("source", fileName);
                if (data.contains("downsizing") && data["downsizing"].toBool())
                    childElement.setAttribute("downsizing", 1);
                if (data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool())
                    childElement.setAttribute("excludeFromExecution", 1);
            }
			else
				childElement.setAttribute("name", childItem->text(0));

			element.appendChild(childElement);

			stack.push(std::make_pair(childItem, childElement));
		}
	}

	std::vector<std::pair<QString, QString> > dependencies = dependencyGraph_.dependencies();
	for (std::size_t i = 0; i < dependencies.size(); ++i)
	{
		QDomElement childElement = doc.createElement("dependency");

		childElement.setAttribute("from", dependencies[i].first);
		childElement.setAttribute("to", dependencies[i].second);

		root.appendChild(childElement);
	}

	return doc;
}
开发者ID:dev-life,项目名称:gideros,代码行数:98,代码来源:librarytreewidget.cpp

示例14: notifyNotVectorLayer

void QgsMapToolReshape::cadCanvasReleaseEvent( QgsMapMouseEvent * e )
{
  //check if we operate on a vector layer //todo: move this to a function in parent class to avoid duplication
  QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );

  if ( !vlayer )
  {
    notifyNotVectorLayer();
    return;
  }

  if ( !vlayer->isEditable() )
  {
    notifyNotEditableLayer();
    return;
  }

  //add point to list and to rubber band
  if ( e->button() == Qt::LeftButton )
  {
    int error = addVertex( e->mapPoint(), e->mapPointMatch() );
    if ( error == 1 )
    {
      //current layer is not a vector layer
      return;
    }
    else if ( error == 2 )
    {
      //problem with coordinate transformation
      emit messageEmitted( tr( "Cannot transform the point to the layers coordinate system" ), QgsMessageBar::WARNING );
      return;
    }

    startCapturing();
  }
  else if ( e->button() == Qt::RightButton )
  {
    deleteTempRubberBand();

    //find out bounding box of mCaptureList
    if ( size() < 1 )
    {
      stopCapturing();
      return;
    }
    QgsPoint firstPoint = points().at( 0 );
    QgsRectangle bbox( firstPoint.x(), firstPoint.y(), firstPoint.x(), firstPoint.y() );
    for ( int i = 1; i < size(); ++i )
    {
      bbox.combineExtentWith( points().at( i ).x(), points().at( i ).y() );
    }

    //query all the features that intersect bounding box of capture line
    QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( bbox ).setSubsetOfAttributes( QgsAttributeList() ) );
    QgsFeature f;
    int reshapeReturn;
    bool reshapeDone = false;

    vlayer->beginEditCommand( tr( "Reshape" ) );
    while ( fit.nextFeature( f ) )
    {
      //query geometry
      //call geometry->reshape(mCaptureList)
      //register changed geometry in vector layer
      QgsGeometry geom = f.geometry();
      if ( !geom.isEmpty() )
      {
        reshapeReturn = geom.reshapeGeometry( points() );
        if ( reshapeReturn == 0 )
        {
          //avoid intersections on polygon layers
          if ( vlayer->geometryType() == QgsWkbTypes::PolygonGeometry )
          {
            //ignore all current layer features as they should be reshaped too
            QMap<QgsVectorLayer*, QSet<QgsFeatureId> > ignoreFeatures;
            ignoreFeatures.insert( vlayer, vlayer->allFeatureIds() );

            if ( geom.avoidIntersections( ignoreFeatures ) != 0 )
            {
              emit messageEmitted( tr( "An error was reported during intersection removal" ), QgsMessageBar::CRITICAL );
              vlayer->destroyEditCommand();
              stopCapturing();
              return;
            }

            if ( geom.isGeosEmpty() ) //intersection removal might have removed the whole geometry
            {
              emit messageEmitted( tr( "The feature cannot be reshaped because the resulting geometry is empty" ), QgsMessageBar::CRITICAL );
              vlayer->destroyEditCommand();
              stopCapturing();
              return;
            }
          }

          vlayer->changeGeometry( f.id(), geom );
          reshapeDone = true;
        }
      }
    }

//.........这里部分代码省略.........
开发者ID:NyakudyaA,项目名称:QGIS,代码行数:101,代码来源:qgsmaptoolreshape.cpp

示例15: clampIndex

    int Pager::insert(int index, const QPixmap & image)
    {
        index = clampIndex(index, true);

        d->images.insert(index, image);
        d->updateScrollBar();
        d->labels.insert(index, QString());
        // Deal with null images FIXME

        // Modify current index if necessary
        if (index <= d->currentIndex && d->images.size() > 0)
        {
            d->currentIndex += 1;
            d->guiIndex += 1.0;
        }

        // Modify index modifiers
        QMap< int, double > updatedModifiers;
        QMutableMapIterator< int, double > iter(d->indexPreModifiers);
        iter.toBack();
        while (iter.hasPrevious())
        {
            iter.previous();
            int targetIndex = iter.key();
            if (targetIndex >= index)
            {
                double modifier = iter.value();
                iter.remove();
                updatedModifiers[targetIndex + 1] = modifier;
            }
            else
            {
                break;
            }
        }
        d->indexPreModifiers.unite(updatedModifiers);

        updatedModifiers.clear();
        iter = d->indexPostModifiers;
        iter.toBack();
        while (iter.hasPrevious())
        {
            iter.previous();
            int targetIndex = iter.key();
            if (targetIndex >= index)
            {
                double modifier = iter.value();
                iter.remove();
                updatedModifiers[targetIndex + 1] = modifier;
            }
            else
            {
                break;
            }
        }
        d->indexPostModifiers.unite(updatedModifiers);

        // Modify transition times
        QMap< int, QTime > updatedTimes;
        QMutableMapIterator< int, QTime > t_iter(d->transitionTimes);
        t_iter.toBack();
        while (t_iter.hasPrevious())
        {
            t_iter.previous();
            int targetIndex = t_iter.key();
            if (targetIndex >= index)
            {
                QTime time = t_iter.value();
                t_iter.remove();
                updatedTimes[targetIndex + 1] = time;
            }
            else
            {
                break;
            }
        }
        d->transitionTimes.unite(updatedTimes);

        // Modify Search Hits
        QMap< int, int > updatedSearchHits;
        QMutableMapIterator< int, int > iter2(d->searchHits);
        iter2.toBack();
        while (iter2.hasPrevious())
        {
            iter2.previous();
            int targetIndex = iter2.key();
            if (targetIndex >= index)
            {
                int hits = iter2.value();
                iter2.remove();
                updatedSearchHits[targetIndex + 1] = hits;
            }
            else
            {
                break;
            }
        }
        d->searchHits.unite(updatedSearchHits);

        // Modify Annotations
//.........这里部分代码省略.........
开发者ID:project-renard-survey,项目名称:utopia-documents-mirror,代码行数:101,代码来源:pager.cpp


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