Example #1
0
QVariant ParameterFileModel::data(const QModelIndex& ind, int role) const {
	// mapper to convert parameter.type into QVariant::Type
	const VarTypeMap& mapper = VarTypeMap::instance();
	int row = ind.row();
	int col = ind.column();
	QString key = _keys[row];
	QString val;
	QVariant res;

	switch (role) {

	case Qt::EditRole:
	case Qt::DisplayRole:
		if ((row >= 0) && (row < _keys.size())) {
			switch (col) {
			case 0:
				// parameter name (without prefix)
				if (!_prefix.isEmpty())
					key.remove(0, _prefix.length());

				// remove dot after valid prefix
				if (key[0] == '.')
					key.remove(0, 1);
				return key;

			case 1:
				if (_parameterFile->isSet(_keys[row])) {
					val = _parameterFile->get(_keys[row]);
				}
				else if (_onlyParams) {
					val = getDefault(_keys[row]);
				}

				// handle parameter links
				if (val.startsWith('@')) {
					QString ref = val.mid(1);
					if(_parameterFile->isSet(ref)) {
						val = _parameterFile->get(ref);
					}
					else if(role == Qt::DisplayRole) {
						val = tr("[invalid reference to %1]").arg(ref);
					}
				}

				// handle QVariant type
				res = val;
				if (_useMetaInfo && isParameter(key)) {
					QString typestring = getType(key);
					QVariant::Type type = mapper[typestring];
					Q_ASSERT(res.canConvert(type));
					res.convert(type);
				}
				return res;

			case 2:
				if (role == Qt::DisplayRole) {
					return QVariant();
				}
				return getValue(key + ".editorpriority").toUInt();
			}
		}
		break;

	case Qt::ToolTipRole:
		if (_useMetaInfo) {
			QString ret = _metaInfos->getDocString(key, getClass(key));
			return ret.isEmpty() ? QVariant() : ret;
		}
		break;

	case Qt::ForegroundRole:
		if (_onlyParams && !isSet(key)) {
			return QColor(Qt::lightGray);
		}
		break;

	case Qt::BackgroundRole:
		switch (getValue(key+".editorpriority").toInt()) {
		case 1:
			return QColor("#8f8");
		case 2:
			return QColor("#ff8");
		case 3:
			return QColor("#f80");
		default:
			break;
		}
		break;

	case Qt::CheckStateRole:
		if (_useMetaInfo && col == 1 &&
				isParameter(key) && getType(key) == "bool") {
			const bool& checked = isSet(key) ?
					QVariant(getValue(key)).toBool() :
					QVariant(getDefault(key)).toBool();
			return checked ? Qt::Checked : Qt::Unchecked;
		}
		break;

	case Qt::StatusTipRole:
		if(col == 1) {
			if (isSet(key)) {
				QString ret = getValue(key);
				if(ret.startsWith('@')) {
					return tr("link to: %1").arg(ret.mid(1));
				}
			}
		}
		break;

	case Qt::DecorationRole:
		if(col == 1) {
			if (isSet(key)) {
				QString ret = getValue(key);
				if(ret.startsWith('@')) {
					return QIcon(":/icons/symlink.png");
				}
			}
		}
		break;

	} // role switch

	return QVariant();
}
Example #2
0
void ServerConfig::load() {
  tree = config.parse();
  valid = tree;

  if (config.getErrors().testFlag(Config::PathNonExistent)) {
    return;
  }

  if (!valid) {
    qCritical() << "Could not load/parse config file:" << config.getPath();
    return;
  }

  // Set the values for type-safe retrieval.
  valid = false;
  qDebug() << "Checking configuration file.. ";

  ConfigTreeNode *node = tree->searchNode("ServerConfig");
  if (!node) {
    qCritical() << "The root element must be 'ServerConfig'!";
    return;
  }

  // ServerConfig/Port
  node = tree->searchNode("ServerConfig/Port");
  if (!node) {
    qCritical() << "Must have an entry 'ServerConfig/Port'!";
    return;
  }
  QVariant var = node->getValue();
  bool ok;
  portVar = var.toString().toUInt(&ok);  
  if (var.isNull() || !ok) {
    qCritical() << "ServerConfig/Port needs to be an unsigned 16-bit integer!";
    return;
  }

  // ServerConfig/SslCert
  node = tree->searchNode("ServerConfig/SslCert");
  if (!node) {
    qCritical() << "Must have an entry 'ServerConfig/SslCert'!";
    return;
  }
  var = node->getValue();
  sslCertVar = var.toString();
  if (var.isNull() || !Ssl::checkCert(sslCertVar).testFlag(Ssl::NoError)) {
    qCritical() << "ServerConfig/SslCert needs to point to a X.509 certificate in PEM format!";
    return;
  }

  // ServerConfig/SslKey
  node = tree->searchNode("ServerConfig/SslKey");
  if (!node) {
    qCritical() << "Must have an entry 'ServerConfig/SslKey'!";
    return;
  }
  var = node->getValue();
  sslKeyVar = var.toString();
  if (var.isNull() || !Ssl::checkKey(sslKeyVar).testFlag(Ssl::NoError)) {
    qCritical() << "ServerConfig/SslKey needs to point to a X.509 private key in PEM format!";
    return;
  }    

  valid = true;
}
Example #3
0
QString
apiVariantToString(const QVariant &variant, bool multiLine)
{
    if (variant.isNull()) {
        return QLatin1String("?");
    }

    if (variant.userType() == QMetaType::Float) {
        return QString::number(variant.toFloat());
    }
    if (variant.userType() == QVariant::Double) {
        return QString::number(variant.toDouble());
    }
    if (variant.userType() == QVariant::ByteArray) {
        if (variant.toByteArray().size() < 1024) {
            int bytes = variant.toByteArray().size();
            return QObject::tr("[binary data, size = %1 bytes]").arg(bytes);
        } else {
            float kb = variant.toByteArray().size()/1024.;
            return QObject::tr("[binary data, size = %1 kb]").arg(kb);
        }
    }

    if (variant.userType() == QVariant::String) {
        return plainTextToHTML(variant.toString(), multiLine);
    }

    if (variant.userType() < QVariant::UserType) {
        return variant.toString();
    }

    if (variant.canConvert<ApiPointer>()) {
        return variant.value<ApiPointer>().toString();
    }
    if (variant.canConvert<ApiBitmask>()) {
        return variant.value<ApiBitmask>().toString();
    }
    if (variant.canConvert<ApiStruct>()) {
        return variant.value<ApiStruct>().toString(multiLine);
    }
    if (variant.canConvert<ApiArray>()) {
        return variant.value<ApiArray>().toString(multiLine);
    }
    if (variant.canConvert<ApiEnum>()) {
        return variant.value<ApiEnum>().toString();
    }

    return QString();
}
Example #4
0
void NcQuickView::keyPressEvent(QKeyEvent *event)
{
    QQuickView::keyPressEvent(event);
    if (event->isAccepted()) return;
	QObject *obj = this->rootObject();
	QObject *timeLine = obj->findChild<QObject*>("slideBar");
	
    switch(event->key()){
		case Qt::Key_C:
			{
				break;
			}
		case Qt::Key_M:
			{	
				std::vector< std::vector<float> > areaSum = this->map->getAreaSum();
				QObject *qchartView = obj->findChild<QObject*>("chart");
			
				QMetaObject::invokeMethod(qchartView, "clearLine");//, Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, i), Q_ARG(QVariant,areaSum[i]));I
				qchartView->setProperty("maxX",(int) areaSum[0].size());

				float maxY = INT_MIN, minY = INT_MAX;
				for (int idx = 0; idx < 3; idx ++)
					for (int i=0;i<areaSum[idx].size();i++)
						{
							maxY = maxY<areaSum[idx][i]?areaSum[idx][i]:maxY;
							minY = minY>areaSum[idx][i]?areaSum[idx][i]:minY;
						}
				qDebug()<<minY<<" "<<maxY;
				qchartView->setProperty("minY",(int)minY*0.9);
				qchartView->setProperty("maxY",(int)maxY*1.1);
				
				for (int idx = 0 ; idx < 3 ; idx++)
				{			
	
					QVariant retValue;	

					
					for (int i=0;i<areaSum[idx].size();i++)
					{
						if (idx == 0) QMetaObject::invokeMethod(qchartView, "createXYPoint1", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, i), Q_ARG(QVariant,areaSum[idx][i]));
						if (idx == 1) QMetaObject::invokeMethod(qchartView, "createXYPoint2", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, i), Q_ARG(QVariant,areaSum[idx][i]));
						if (idx == 2) QMetaObject::invokeMethod(qchartView, "createXYPoint3", Q_RETURN_ARG(QVariant, retValue), Q_ARG(QVariant, i), Q_ARG(QVariant,areaSum[idx][i]));	
					}
					qDebug()<<retValue.toString();
				}
				
					qDebug()<<"qchart is fixed";
				
				break;
			}
        default:
			this->map->keyPressEvent(event);
    }
/*
	int timeStamp = this->map->getTimestamp();
	if (timeLine)
	//	timeLine->setProperty("x",timeStamp * 10);	
	//	timeLine->setProperty("timeStamp",timeStamp);	
	
	else qDebug()<<"didnt find QML component";
  */
    NcQuickView::update();
}
Example #5
0
static QString msgCannotWriteProperty(const QString &pname, const QVariant &v)
{
    return QCoreApplication::translate("QFormBuilder", "The property %1 could not be written. The type %2 is not supported yet.").
           arg(pname).arg(QLatin1String(v.typeName()));

}
Example #6
0
enum SetResponse itemPricingSchedule::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;

      _name->setFocus();
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

      _save->setFocus();
    }
    else if (param.toString() == "copy")
    {
      _mode = cCopy;

      _name->setFocus();
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _name->setEnabled(FALSE);
      _descrip->setEnabled(FALSE);
      _dates->setEnabled(FALSE);
      _currency->setEnabled(FALSE);
      _new->setEnabled(FALSE);
      _close->setText(tr("&Close"));
      _save->hide();

      _close->setFocus();
    }
  }

  param = pParams.value("ipshead_id", &valid);
  if (valid)
  {
    _ipsheadid = param.toInt();
    populate();
  }

  if ( (_mode == cNew) || (_mode == cEdit) || (_mode == cCopy) )
  {
    connect(_ipsitem, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool)));
    connect(_ipsitem, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool)));
    connect(_ipsitem, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick()));
  }

  if ( (_mode == cNew) || (_mode == cCopy) )
  {
    int oldIpsheadid = _ipsheadid;
    q.exec("SELECT NEXTVAL('ipshead_ipshead_id_seq') AS ipshead_id;");
    if (q.first())
      _ipsheadid = q.value("ipshead_id").toInt();

    if(_mode == cCopy)
    {
      q.prepare(" INSERT "
                "   INTO ipsitem "
                "       (ipsitem_ipshead_id, ipsitem_item_id, "
                "        ipsitem_qtybreak, ipsitem_price,"
                "        ipsitem_qty_uom_id, ipsitem_price_uom_id) "
                " SELECT :ipshead_id, ipsitem_item_id, "
                "        ipsitem_qtybreak, ipsitem_price,"
                "        ipsitem_qty_uom_id, ipsitem_price_uom_id "
                "   FROM ipsitem "
                "  WHERE (ipsitem_ipshead_id=:oldipshead_id); "
                " INSERT "
                "   INTO ipsprodcat "
                "       (ipsprodcat_ipshead_id, ipsprodcat_prodcat_id, "
                "        ipsprodcat_qtybreak, ipsprodcat_discntprcnt) "
                " SELECT :ipshead_id, ipsprodcat_prodcat_id, "
                "        ipsprodcat_qtybreak, ipsprodcat_discntprcnt "
                "   FROM ipsprodcat "
                "  WHERE (ipsprodcat_ipshead_id=:oldipshead_id); ");
      q.bindValue(":ipshead_id", _ipsheadid);
      q.bindValue(":oldipshead_id", oldIpsheadid);
      q.exec();
    }
  }

  return NoError;
}
int QgsAtlasComposition::updateFeatures()
{
  //needs to be called when layer, filter, sort changes

  if ( !mCoverageLayer )
  {
    return 0;
  }

  updateFilenameExpression();

  // select all features with all attributes
  QgsFeatureIterator fit = mCoverageLayer->getFeatures();

  std::auto_ptr<QgsExpression> filterExpression;
  if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
  {
    filterExpression = std::auto_ptr<QgsExpression>( new QgsExpression( mFeatureFilter ) );
    if ( filterExpression->hasParserError() )
    {
      throw std::runtime_error( tr( "Feature filter parser error: %1" ).arg( filterExpression->parserErrorString() ).toLocal8Bit().data() );
    }
  }

  // We cannot use nextFeature() directly since the feature pointer is rewinded by the rendering process
  // We thus store the feature ids for future extraction
  QgsFeature feat;
  mFeatureIds.clear();
  mFeatureKeys.clear();
  while ( fit.nextFeature( feat ) )
  {
    if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
    {
      QVariant result = filterExpression->evaluate( &feat, mCoverageLayer->pendingFields() );
      if ( filterExpression->hasEvalError() )
      {
        throw std::runtime_error( tr( "Feature filter eval error: %1" ).arg( filterExpression->evalErrorString() ).toLocal8Bit().data() );
      }

      // skip this feature if the filter evaluation if false
      if ( !result.toBool() )
      {
        continue;
      }
    }
    mFeatureIds.push_back( feat.id() );

    if ( mSortFeatures )
    {
      mFeatureKeys.insert( feat.id(), feat.attributes()[ mSortKeyAttributeIdx ] );
    }
  }

  // sort features, if asked for
  if ( mSortFeatures )
  {
    FieldSorter sorter( mFeatureKeys, mSortAscending );
    qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter );
  }

  QgsExpression::setSpecialColumn( "$numfeatures", QVariant(( int )mFeatureIds.size() ) );

  //jump to first feature if currently using an atlas preview
  //need to do this in case filtering/layer change has altered matching features
  if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas )
  {
    firstFeature();
  }

  return mFeatureIds.size();
}
Example #8
0
bool CQSpecieDM::specieDataChange(
  UndoSpeciesData *pUndoSpeciesData,
  const QVariant &value,
  int column)
{
  switchToWidget(CCopasiUndoCommand::SPECIES);

  GET_MODEL_OR(pModel, return false);

  mpSpecies =
    dynamic_cast<CMetab*>(pUndoSpeciesData->getObject(pModel));

  if (mpSpecies == NULL)
    return false;

  const CCompartment * pCompartment = NULL;

  if (column == COL_COMPARTMENT ||
      column == COL_ICONCENTRATION ||
      column == COL_INUMBER)
    {
      try
        {
          pCompartment = mpSpecies->getCompartment();
        }
      catch (...) {}
    }

  if (column == COL_NAME_SPECIES)
    {
      mpSpecies->setObjectName(TO_UTF8(value.toString()));
      pUndoSpeciesData->setCN(mpSpecies->getCN());
    }
  else if (column == COL_COMPARTMENT)
    {
      // This must be set first for setInitialConcentration and
      // setInitialNumber to work correctly.
      std::string Compartment(TO_UTF8(value.toString()));

      if (Compartment != pCompartment->getObjectName())
        {
          std::string CompartmentToRemove = mpSpecies->getCompartment()->getObjectName();

          if (!(pModel->getCompartments()[Compartment].addMetabolite(mpSpecies)))
            {
              QString msg;
              msg = "Unable to move species '" + FROM_UTF8(mpSpecies->getObjectName()) + "'\n"
                    + "from compartment '" + FROM_UTF8(CompartmentToRemove) + "' to compartment '" + FROM_UTF8(Compartment) + "'\n"
                    + "since a species with that name already exist in the target compartment.";

              CQMessageBox::information(NULL,
                                        "Unable to move Species",
                                        msg,
                                        QMessageBox::Ok, QMessageBox::Ok);
              return false;
            }
          else
            {
              pModel->getCompartments()[CompartmentToRemove].getMetabolites().remove(mpSpecies->getObjectName());
              pModel->setCompileFlag();
              pModel->initializeMetabolites();

              if (mpSpecies && pCompartment)
                {
                  C_FLOAT64 Factor = 1.0 / pCompartment->getInitialValue();
                  Factor *= pCompartment->getInitialValue();

                  mpSpecies->setInitialValue(Factor * pUndoSpeciesData->getINumber());
                  mpSpecies->setValue(Factor * mpSpecies->getValue());
                }

              emit notifyGUI(ListViews::METABOLITE, ListViews::CHANGE, mpSpecies->getKey());
              emit notifyGUI(ListViews::COMPARTMENT, ListViews::CHANGE, pCompartment->getKey());
            }
        }
    }
  else if (column == COL_TYPE_SPECIES)
    mpSpecies->setStatus((CModelEntity::Status) mItemToType[value.toInt()]);
  else if (column == COL_ICONCENTRATION)
    {
      if (mFlagConc)
        mpSpecies->setInitialConcentration(value.toDouble());

      if (mpSpecies && pCompartment)
        {
          const C_FLOAT64 initialValue =
            CMetab::convertToNumber(pUndoSpeciesData->getIConc(),
                                    *pCompartment,
                                    *pModel);
          mpSpecies->setInitialValue(initialValue);
        }
    }
  else if (column == COL_INUMBER)
    {
      if (!mFlagConc)
        mpSpecies->setInitialValue(value.toDouble());

      if (mpSpecies && pCompartment)
        {
          mpSpecies->setInitialConcentration(
            CMetab::convertToConcentration(pUndoSpeciesData->getINumber(),
                                           *pCompartment,
                                           *pModel)
          );
        }
    }

  //Save Key
  std::string key = mpSpecies->getKey();

  // ask for refresh this may change the key!
  QModelIndex index = getIndexFor(mpSpecies, column);
  emit dataChanged(index, index);

  if (column == COL_NAME_SPECIES)
    {
      emit notifyGUI(ListViews::METABOLITE, ListViews::RENAME, key);
    }
  else
    {
      emit notifyGUI(ListViews::METABOLITE, ListViews::CHANGE, key);
    }

  return true;
}
Example #9
0
QPair<QVariant, QVariant>
RemapHDF4::rawValue(int d, int w, int h)
{
  QPair<QVariant, QVariant> pair;

  if (d < 0 || d >= m_depth ||
      w < 0 || w >= m_width ||
      h < 0 || h >= m_height)
    {
      pair.first = QVariant("OutOfBounds");
      pair.second = QVariant("OutOfBounds");
      return pair;
    }

  uchar *hdftmp = new uchar[m_bytesPerVoxel];
  int32 start[2], edges[2];
  start[0] = w;
  start[1] = h;
  edges[0] = 1;
  edges[1] = 1;

  int32 sd_id = SDstart(m_imageList[d].toAscii().data(),
			DFACC_READ);
  int32 sds_id = SDselect(sd_id, m_Index);
  int status = SDreaddata(sds_id,
			  start, NULL, edges,
			  (VOIDP)hdftmp);
  if (status == -1)
    QMessageBox::information(0, "error", "Cannot read");

  status = SDendaccess(sds_id);
  status = SDend(sd_id);


  QVariant v;

  if (m_voxelType == _UChar)
    {
      uchar *aptr = (uchar*) hdftmp;
      uchar a = *aptr;
      v = QVariant((uint)a);
    }
  else if (m_voxelType == _Char)
    {
      char *aptr = (char*) hdftmp;
      char a = *aptr;
      v = QVariant((int)a);
    }
  else if (m_voxelType == _UShort)
    {
      ushort *aptr = (ushort*) hdftmp;
      ushort a = *aptr;
      v = QVariant((uint)a);
    }
  else if (m_voxelType == _Short)
    {
      short *aptr = (short*) hdftmp;
      short a = *aptr;
      v = QVariant((int)a);
    }
  else if (m_voxelType == _Int)
    {
      int *aptr = (int*) hdftmp;
      int a = *aptr;
      v = QVariant((int)a);
    }
  else if (m_voxelType == _Float)
    {
      float *aptr = (float*) hdftmp;
      double a = *aptr;
      v = QVariant((double)a);
    }

  int rawSize = m_rawMap.size()-1;
  int idx = rawSize;
  float frc = 0;
  float val;

  if (v.type() == QVariant::UInt)
    val = v.toUInt();
  else if (v.type() == QVariant::Int)
    val = v.toInt();
  else if (v.type() == QVariant::Double)
    val = v.toDouble();


  if (val <= m_rawMap[0])
    {
      idx = 0;
      frc = 0;
    }
  else if (val >= m_rawMap[rawSize])
    {
      idx = rawSize-1;
      frc = 1;
    }
  else
    {
      for(uint m=0; m<rawSize; m++)
	{
	  if (val >= m_rawMap[m] &&
	      val <= m_rawMap[m+1])
	    {
	      idx = m;
	      frc = ((float)val-(float)m_rawMap[m])/
		((float)m_rawMap[m+1]-(float)m_rawMap[m]);
	    }
	}
    }
  
  uchar pv = m_pvlMap[idx] + frc*(m_pvlMap[idx+1]-m_pvlMap[idx]);

  pair.first = v;
  pair.second = QVariant((uint)pv);
  return pair;
}
Example #10
0
int main(int argc, char **argv)
{
	KAboutData about("kdedtester", I18N_NOOP("KDED Module tester"), version, description,
		     KAboutData::License_GPL, "(C) 2004 Diego 'Flameeyes' Pettenò", 0, 0, "[email protected]");
	about.addAuthor( "Diego 'Flameeyes' Pettenò", 0, "[email protected]" );
	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions( options );
	KApplication app;

	// no session.. just start up normally
	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
	
	if ( args->count() == 0 )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}

	/// @todo do something with the command line args here
	QCString modulename = args->arg(0);
	args->clear();
	
	if ( modulename.isEmpty() )
	{
		kdError() << "You must call kdedtester with a valid kded module name." << endl;
		return -1;
	}
	
	KService::Ptr s = KService::serviceByDesktopPath("kded/"+modulename+".desktop");
	if ( ! s || s->library().isEmpty() )
	{
		kdError() << "Unable to load the service for requested module." << endl;
		return -2;
	}
	
	// get the library loader instance
	KLibLoader *loader = KLibLoader::self();
	
	QVariant v = s->property("X-KDE-Factory");
	QString factory = v.isValid() ? v.toString() : QString::null;
	if (factory.isEmpty())
		factory = s->library();

	factory = "create_" + factory;
	QString libname = "kded_"+s->library();
	
	kdWarning() << "Recap: the factory is '" << factory << "', and the library '" << libname << "'." << endl;

	KLibrary *lib = loader->library(QFile::encodeName(libname));
	if ( ! lib )
	{
		kdWarning() << "Library not found, trying '" << libname << "' instead" << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		
		libname.prepend("lib");
		lib = loader->library(QFile::encodeName(libname));
	}
	
	if ( ! lib )
	{
		kdError() << "Library still not found. Exiting." << endl
			<< "KLibLoader says: " << loader->lastErrorMessage() << endl;
		return -3;
	}
	
	void *create = lib->symbol(QFile::encodeName(factory));
	if ( ! create )
	{
		kdError() << "Unable to find factory symbol into library. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -4;
	}
	
        KDEDModule* (*func)(const QCString &);
        func = (KDEDModule* (*)(const QCString &)) create;
	
	KDEDModule *module = func(modulename);
	if ( ! module )
	{
		kdError() << "Factory returned NULL module. Exiting." << endl;
		loader->unloadLibrary(QFile::encodeName(libname));
		return -5;
	}
	
	delete module;
	loader->unloadLibrary(QFile::encodeName(libname));
	kdWarning() << "Module loaded (and already unloaded) correctly." << endl;
	return 0;
}
Example #11
0
bool CQSpecieDM::setData(const QModelIndex &index, const QVariant &value,
                         int role)
{
  //change is only accepted if the new value is different from the old value and also the old value is not equal to "New Species" for the 'name' column
  // in that case no new species will be created!
  if (index.data() == value)
    return false;

  if (index.column() == COL_TYPE_SPECIES &&
      index.data().toString() == QString(FROM_UTF8(CModelEntity::StatusName[mItemToType[value.toInt()]])))
    return false;

  if (index.column() == COL_COMPARTMENT && value == "")
    return false;

  bool defaultRow = isDefaultRow(index);

  if (defaultRow)
    {
      mpUndoStack->push(new InsertSpecieRowsCommand(rowCount(), 1, this, index, value));
    }
  else
    {
      mpUndoStack->push(new SpecieDataChangeCommand(mpSpecies, value, index.data(), index.column(), this));
    }

  return true;
}
Example #12
0
enum SetResponse voucherItem::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("curr_id", &valid);
  if (valid)
  {
    _freightToVoucher->setId(param.toInt());
	_tax->setId(param.toInt());
  }

  param = pParams.value("effective", &valid);
  if (valid)
  {
	_freightToVoucher->setEffective(param.toDate());
	_tax->setEffective(param.toDate());
  }

  param = pParams.value("vohead_id", &valid);
  if (valid)
  {
    _voheadid = param.toInt();
    q.prepare("SELECT vohead_taxzone_id "
	          "FROM vohead "
	          "WHERE (vohead_id = :vohead_id);");
    q.bindValue(":vohead_id", _voheadid);
    q.exec();
    if (q.first())
      _taxzoneid = q.value("vohead_taxzone_id").toInt();
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
      return UndefinedError;
    }
	else
	  _taxzoneid = -1;
  }
  else
    _voheadid = -1;

  param = pParams.value("poitem_id", &valid);
  if (valid)
  {
    _poitemid = param.toInt();

    q.prepare( "SELECT pohead_number, poitem_linenumber, poitem_taxtype_id, "
               "       COALESCE(itemsite_id, -1) AS itemsiteid,"
               "       poitem_vend_item_number, poitem_vend_uom, poitem_vend_item_descrip,"
               "       poitem_duedate,"
               "       poitem_qty_ordered,"
               "       poitem_qty_received,"
               "       poitem_qty_returned,"
               "       ( SELECT COALESCE(SUM(porecv_qty), 0)"
               "                    FROM porecv"
               "                    WHERE ( (porecv_posted)"
               "                     AND (NOT porecv_invoiced)"
       	       "                     AND (porecv_vohead_id IS NULL)"
               "                     AND (porecv_poitem_id=poitem_id) ) ) AS f_received,"
               "       ( SELECT COALESCE(SUM(poreject_qty), 0)"
               "                    FROM poreject"
               "                    WHERE ( (poreject_posted)"
               "                     AND (NOT poreject_invoiced)"
               "                     ANd (poreject_vohead_id IS NULL)"
               "                     AND (poreject_poitem_id=poitem_id) ) ) AS f_rejected,"
               "       poitem_unitprice,"
               "       poitem_unitprice * poitem_qty_ordered AS f_extprice,"
               "       poitem_freight "
               "FROM pohead, "
	       " poitem LEFT OUTER JOIN itemsite ON (poitem_itemsite_id=itemsite_id) "
           "WHERE ( (poitem_pohead_id=pohead_id)"
               " AND (poitem_id=:poitem_id) );" );
    q.bindValue(":poitem_id", _poitemid);
    q.exec();
    if (q.first())
    {
      _poNumber->setText(q.value("pohead_number").toString());
      _lineNumber->setText(q.value("poitem_linenumber").toString());
      _vendItemNumber->setText(q.value("poitem_vend_item_number").toString());
      _vendUOM->setText(q.value("poitem_vend_uom").toString());
      _vendDescription->setText(q.value("poitem_vend_item_descrip").toString());
      _dueDate->setDate(q.value("poitem_duedate").toDate());
      _ordered->setText(q.value("poitem_qty_ordered").toDouble());
      _received->setText(q.value("poitem_qty_received").toDouble());
      _rejected->setText(q.value("poitem_qty_returned").toDouble());
      _uninvoicedReceived->setText(q.value("f_received").toDouble());
      _uninvoicedRejected->setText(q.value("f_rejected").toDouble());
      _unitPrice->setText(q.value("poitem_unitprice").toDouble());
      _extPrice->setText(q.value("f_extprice").toDouble());
      _lineFreight->setText(q.value("poitem_freight").toDouble());
	  _taxtype->setId(q.value("poitem_taxtype_id").toInt());
      if (q.value("itemsiteid") != -1)
        _item->setItemsiteid(q.value("itemsiteid").toInt());
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                  __FILE__, __LINE__);
      reject();
      return UndefinedError;
    }
  }
  else
    _poitemid = -1;

  if ( (_voheadid != -1) && (_poitemid != -1) )
  {
    q.prepare( "SELECT voitem_id, voitem_close, voitem_taxtype_id, "
               "       voitem_qty,"
               "       voitem_freight "
               "FROM voitem "
               "WHERE ( (voitem_vohead_id=:vohead_id)"
               " AND (voitem_poitem_id=:poitem_id) );" );
    q.bindValue(":vohead_id", _voheadid);
    q.bindValue(":poitem_id", _poitemid);
    q.exec();
    if (q.first())
    {
      _voitemid = q.value("voitem_id").toInt();
      _closePoitem->setChecked(q.value("voitem_close").toBool());
      _qtyToVoucher->setText(q.value("voitem_qty").toDouble());
      _freightToVoucher->setLocalValue(q.value("voitem_freight").toDouble());
      _taxtype->setId(q.value("voitem_taxtype_id").toInt());
    }
    else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                  __FILE__, __LINE__);
      reject();
      return UndefinedError;
    }
    else
    {
      _voitemid = -1;
      _closePoitem->setChecked(FALSE);
      _qtyToVoucher->clear();
      _freightToVoucher->clear();
    }

	q.prepare( "SELECT SUM(COALESCE(taxhist_tax, 0.00)) AS taxamt "
	           "FROM voitem LEFT OUTER JOIN voitemtax "
			   " ON (voitem_id = taxhist_parent_id) "
               "WHERE ( (voitem_vohead_id=:vohead_id)"
               " AND (voitem_poitem_id=:poitem_id) );" );
    q.bindValue(":vohead_id", _voheadid);
    q.bindValue(":poitem_id", _poitemid);
    q.exec();
    if (q.first())
	  _tax->setLocalValue(q.value("taxamt").toDouble());
	else if (q.lastError().type() != QSqlError::NoError)
    {
      systemError(this, _rejectedMsg.arg(q.lastError().databaseText()),
                  __FILE__, __LINE__);
      reject();
      return UndefinedError;
    }
    else
      _tax->clear();
  }

  sFillList();
  _saved = TRUE;
  return NoError;
}
bool ParseTreeModel::setData(const QModelIndex &index, const QVariant &value,
                             int role)
{
    if(role != Qt::EditRole)
        return false;

    if(index.column() != valueColumn)
        return false;

    ParseTreeNode* node = static_cast<ParseTreeNode*>
                             (index.internalPointer());

    if(node->isParam())
    {
        struct skin_tag_parameter* param = node->getParam();

        /* Now that we've established that we do, in fact, have a parameter,
         * set it to its new value if an acceptable one has been entered
         */
        if(value.toString().trimmed() == QString(QChar(DEFAULTSYM)))
        {
            if(islower(param->type_code))
                param->type = skin_tag_parameter::DEFAULT;
            else
                return false;
        }
        else if(tolower(param->type_code) == 's'
                || tolower(param->type_code) == 'f')
        {
            if(param->type == skin_tag_parameter::STRING)
                free(param->data.text);

            param->type = skin_tag_parameter::STRING;
            param->data.text = strdup(value.toString().trimmed().toAscii());
        }
        else if(tolower(param->type_code) == 'i')
        {
            if(!value.canConvert(QVariant::Int))
                return false;

            param->type = skin_tag_parameter::INTEGER;
            param->data.number = value.toInt();
        }
        else
        {
            return false;
        }
    }
    else
    {
        struct skin_element* element = node->getElement();

        if(element->type != COMMENT && element->type != TEXT)
            return false;

        free(element->data);
        element->data = strdup(value.toString().trimmed().toAscii());
    }

    emit dataChanged(index, index);
    return true;
}
void QtPropertyDataDavaVariant::SetValueInternal(const QVariant &value)
{
	switch(curVariantValue.type)
	{
	case DAVA::VariantType::TYPE_BOOLEAN:
		curVariantValue.SetBool(value.toBool());
		break;
	case DAVA::VariantType::TYPE_FLOAT:
		curVariantValue.SetFloat(value.toFloat());
		break;
	case DAVA::VariantType::TYPE_INT32:
		curVariantValue.SetInt32(value.toInt());
		break;
	case DAVA::VariantType::TYPE_INT64:
		curVariantValue.SetInt64(value.toLongLong());
		break;
	case DAVA::VariantType::TYPE_UINT32:
		curVariantValue.SetUInt32(value.toUInt());
		break;
	case DAVA::VariantType::TYPE_UINT64:
		curVariantValue.SetUInt64(value.toULongLong());
		break;
	case DAVA::VariantType::TYPE_KEYED_ARCHIVE:
		ToKeyedArchive(value);
		break;
	case DAVA::VariantType::TYPE_STRING:
		curVariantValue.SetString(value.toString().toStdString());
		break;
	case DAVA::VariantType::TYPE_MATRIX2:
		ToMatrix2(value);
		break;
	case DAVA::VariantType::TYPE_MATRIX3:
		ToMatrix3(value);
		break;
	case DAVA::VariantType::TYPE_MATRIX4:
		ToMatrix4(value);
		break;
	case DAVA::VariantType::TYPE_VECTOR2:
		ToVector2(value);
		break;
	case DAVA::VariantType::TYPE_VECTOR3:
		ToVector3(value);
		break;
	case DAVA::VariantType::TYPE_VECTOR4:
		ToVector4(value);
		break;
    case DAVA::VariantType::TYPE_COLOR:
        ToColor(value);
        break;
    case DAVA::VariantType::TYPE_FASTNAME:
        curVariantValue.SetFastName(DAVA::FastName(value.toString().toStdString().c_str()));
        break;
	case DAVA::VariantType::TYPE_AABBOX3:
		ToAABBox3(value);
		break;

	case DAVA::VariantType::TYPE_BYTE_ARRAY:
	default:
		break;
	}
}
Example #15
0
QVariant IdListHelper::toVariant(IdList const &list)
{
	QVariant v;
	v.setValue(list);
	return v;
}
Example #16
0
	QString LogError::insertArgs(const QString &rMessage) const
	{
	    QString result;
	    
	    /*
	     
	    // Don't use a loop to be able to handle arguments that conatin strings
	    // like %1.
	    // Using this method only 9 arguments can be handled as the %1
	    // in %11 gets also replaced with the first argument.
	
	    switch (mArgs.count())
	    {
	        case 0:
	            break;
	        case 1:
	            result = rMessage.arg(mArgs.at(0));
	            break;
	        case 2:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1));
	            break;
	        case 3:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2));
	            break;
	        case 4:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3));
	            break;
	        case 5:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4));
	            break;
	        case 6:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5));
	            break;
	        case 7:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6));
	            break;
	        case 8:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6), mArgs.at(7));
	            break;
	        default:
	            result = rMessage.arg(mArgs.at(0), mArgs.at(1), mArgs.at(2), mArgs.at(3), mArgs.at(4), mArgs.at(5), mArgs.at(6), mArgs.at(7), mArgs.at(8));
	            break;
	    }
	
	    if (mArgs.count() > 9)
	    {
	        int i = 9;
	        while(i < mArgs.count())
	        {
	            result = result.arg(mArgs.at(i));
	            i++;
	        }
	    }
	    */
	    
	    result = rMessage;
	    QVariant arg;
	    Q_FOREACH(arg, mArgs)
	        result = result.arg(arg.toString());
	    return result;
	}
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
QDataStream out(...);
QVariant v(123);                // The variant now contains an int
int x = v.toInt();              // x = 123
out << v;                       // Writes a type tag and an int to out
v = QVariant("hello");          // The variant now contains a QByteArray
v = QVariant(tr("hello"));      // The variant now contains a QString
int y = v.toInt();              // y = 0 since v cannot be converted to an int
QString s = v.toString();       // s = tr("hello")  (see QObject::tr())
out << v;                       // Writes a type tag and a QString to out
...
QDataStream in(...);            // (opening the previously written stream)
in >> v;                        // Reads an Int variant
int z = v.toInt();              // z = 123
qDebug("Type is %s",            // prints "Type is int"
        v.typeName());
v = v.toInt() + 100;            // The variant now hold the value 223
v = QVariant(QStringList());
Example #18
0
bool Bookmarks::updateBookmarkState(const QString &type, const QVariant &data, bool state)
{
    if (type == "Verses" || type == tr("Verses")) {
        QDomElement verseNode = findChildNode("folder", "Verses");
        if (verseNode.isNull()) {
            QDomElement root = m_domDocument.createElement("folder");
            QDomElement child = m_domDocument.createElement("title");
            QDomText newTitleText = m_domDocument.createTextNode(tr("Verses"));
            root.setAttribute("folded", "no");
            child.appendChild(newTitleText);
            root.appendChild(child);
            m_domDocument.documentElement().appendChild(root);
            verseNode = root;
            parseFolderElement(root);
        }

        QTreeWidgetItem* parentItem = m_domElementForItem.key(verseNode);
        //REMOVE OPERATION
        if (!state) {
            int countOfChildren = parentItem->childCount();
            int numOfDel = 0;
            bool allMatchedRemoved = true;
            for (int i = 0; i < countOfChildren; ++i) {
                QTreeWidgetItem* childItem = parentItem->child(i);
                if (!childItem) {
                    continue;
                }

                if (childItem->data(0, Qt::UserRole).toString() == data.toStringList().at(0) + "|" + data.toStringList().at(1)) {
                    ++numOfDel;

                    if (unBookmarkItem(childItem)) {
                        --i; //because one of children was deleted
                        --countOfChildren;
                    }
                    else {
                        allMatchedRemoved = false;
                    }
                }
            }

            //allMatchedRemoved is false when at least one of
            // matched items are not deleted!!
            return allMatchedRemoved;
        }

        QDomElement bookmark = m_domDocument.createElement("bookmark");
        QDomElement bookmarkTitle = m_domDocument.createElement("title");
        QDomElement bookmarkDescription = m_domDocument.createElement("desc");
        QDomElement bookmarkInfo = m_domDocument.createElement("info");
        QDomElement infoMetaData = m_domDocument.createElement("metadata");

        infoMetaData.setAttribute("owner", "http://saaghar.pozh.org");
        QDomText bookmarkSaagharMetadata = m_domDocument.createTextNode(data.toStringList().at(0) + "|" + data.toStringList().at(1));
        infoMetaData.appendChild(bookmarkSaagharMetadata);
        bookmarkInfo.appendChild(infoMetaData);
        bookmark.appendChild(bookmarkTitle);
        bookmark.appendChild(bookmarkDescription);
        bookmark.appendChild(bookmarkInfo);
        verseNode.appendChild(bookmark);

        qDebug() << data << state;
        QDomElement firstChild = m_domDocument.documentElement().firstChildElement("folder");
        firstChild.text();
        QTreeWidgetItem* item = createItem(bookmark, parentItem);
        item->setIcon(0, m_bookmarkIcon);

        QString title = data.toStringList().at(2);
        item->setText(0, title);
        item->setToolTip(0, title);
        item->setData(0, Qt::UserRole, data.toStringList().at(0) + "|" + data.toStringList().at(1));
        item->setData(1, Qt::UserRole, data.toStringList().at(3));
        if (data.toStringList().size() == 5) {
            item->setText(1, data.toStringList().at(4));
            item->setToolTip(1, data.toStringList().at(4));
        }

        if (parentItem->childCount() == 1) {
            resizeColumnToContents(0);
            resizeColumnToContents(1);
        }

        return true;
    }

    //an unknown type!!
    return false;
}
Example #19
0
/*!
    \fn Ebackup::generar_config()
    Genera un una copia de los valores de configuracion del programa y los prepara para la compresion.
 */
bool Ebackup::generar_config()
{
 preferencias *p = preferencias::getInstancia();
 // Obtengo todas las claves
 QStringList claves = p->allKeys();
 PBProgreso->setRange( 0, ( claves.size() * 2 ) + 2 );
 PBProgreso->setValue( 0 );
 // Genero los datos concatenando las variables
 // Inicio de preferencias
 // Cabecera de los datos
 datos->append("|->preferencias->");
 // bucle que recorre cada valor
 QStringList::const_iterator iterador;
 for( iterador = claves.constBegin(); iterador != claves.constEnd(); ++iterador )
 {
        if( !_continuar )
        { return false; }
   datos->append( (*iterador).toLocal8Bit().constData() );
   PBProgreso->setValue( PBProgreso->value() + 1 );
   datos->append( "=" );
   // Separador de valores
   QVariant v = p->value( (*iterador), QVariant() );
   QString result;
   switch( v.type() )
   {
        ///////////////////////////////////////////////////////////////////////////
        // Copiado desde la clase qsettings de qt
       case QVariant::Invalid:
       {
            result = QLatin1String("@Invalid()");
            break;
       }

        case QVariant::ByteArray:
        {
            QByteArray a = v.toByteArray();
            result = QLatin1String("@ByteArray(");
            result += QString::fromLatin1(a.constData(), a.size());
            result += QLatin1Char(')');
            break;
        }

        case QVariant::String:
        case QVariant::LongLong:
        case QVariant::ULongLong:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::Bool:
        case QVariant::Double:
        case QVariant::KeySequence: {
            result = v.toString();
            if (result.startsWith(QLatin1Char('@')))
                result.prepend(QLatin1Char('@'));
            break;
        }
        case QVariant::Rect: {
            QRect r = qvariant_cast<QRect>(v);
            result += QLatin1String("@Rect(");
            result += QString::number(r.x());
            result += QLatin1Char(' ');
            result += QString::number(r.y());
            result += QLatin1Char(' ');
            result += QString::number(r.width());
            result += QLatin1Char(' ');
            result += QString::number(r.height());
            result += QLatin1Char(')');
            break;
        }
        case QVariant::Size: {
            QSize s = qvariant_cast<QSize>(v);
            result += QLatin1String("@Size(");
            result += QString::number(s.width());
            result += QLatin1Char(' ');
            result += QString::number(s.height());
            result += QLatin1Char(')');
            break;
        }
        case QVariant::Point: {
            QPoint p = qvariant_cast<QPoint>(v);
            result += QLatin1String("@Point(");
            result += QString::number(p.x());
            result += QLatin1Char(' ');
            result += QString::number(p.y());
            result += QLatin1Char(')');
            break;
        }
        default: {
            QByteArray a;
            {
                QDataStream s(&a, QIODevice::WriteOnly);
                s.setVersion(QDataStream::Qt_4_0);
                s << v;
            }

            result = QLatin1String("@Variant(");
            result += QString::fromLatin1(a.constData(), a.size());
            result += QLatin1Char(')');
            break;
        }
        //////////////////////////////////////////////////////////////////////////////
    }
    datos->append( result );
    PBProgreso->setValue( PBProgreso->value() + 1 );
   // Separador de preferencia
   datos->append( "\n" );
 }
 // fin de los datos
 datos->append("<-preferencias<-|");
 // Comprimo los datos y los envio al buffer de comprimidos
 LDebug->setText( LDebug->text() + "... Comprimiendo.... " );
 comprimir();
 PBProgreso->setValue( PBProgreso->value() + 1 );
 // Limpio el buffer asi se libera la memoria
 LDebug->setText( LDebug->text() + "... Limpiando.... " );
 datos->clear();
 PBProgreso->setValue( PBProgreso->value() + 1 );
 LDebug->setText( "Listo backup de configuracion" );
 return true;
}
Example #20
0
bool ctkLDAPExpr::compare( const QVariant &obj, int op, const QString &s ) const
{
  if (obj.isNull())
    return false;
  if (op == EQ && s == WILDCARD_QString )
    return true;
  try {
    if ( obj.canConvert<QString>( ) ) {
      return compareQString(obj.toString(), op, s);
    } else if (obj.canConvert<char>( ) ) {
      return compareQString(obj.toString(), op, s);
    } else if (obj.canConvert<bool>( ) ) {
      if (op==LE || op==GE)
        return false;
      if ( obj.toBool() ) {
        return s.compare("true", Qt::CaseInsensitive);
      } else {
        return s.compare("false", Qt::CaseInsensitive);
      }
    } 
    else if ( obj.canConvert<Byte>( ) || obj.canConvert<int>( ) ) 
    {
      switch(op) {
      case LE:
        return obj.toInt() <= s.toInt();
      case GE:
        return obj.toInt() >= s.toInt();
      default: /*APPROX and EQ*/
        return s.toInt( ) == obj.toInt();
      }
    } else if ( obj.canConvert<float>( ) ) {
      switch(op) {
      case LE:
        return obj.toFloat() <= s.toFloat();
      case GE:
        return obj.toFloat() >= s.toFloat();
      default: /*APPROX and EQ*/
        return s.toFloat() == obj.toFloat();
      }
    } else if (obj.canConvert<double>()) {
      switch(op) {
      case LE:
        return obj.toDouble() <= s.toDouble();
      case GE:
        return obj.toDouble() >= s.toDouble();
      default: /*APPROX and EQ*/
        return s.toDouble( ) == obj.toDouble( );
      }
    } else if (obj.canConvert<qlonglong>( )) {
      switch(op) {
      case LE:
        return obj.toLongLong() <= s.toLongLong( );
      case GE:
        return obj.toLongLong() >= s.toLongLong( );
      default: /*APPROX and EQ*/
        return obj.toLongLong() == s.toLongLong( );
      }
    } 
    else if (obj.canConvert< QList<QVariant> >()) {
      QList<QVariant> list = obj.toList();
      QList<QVariant>::Iterator it;
      for (it=list.begin(); it != list.end( ); it++)
         if (compare(*it, op, s))
           return true;
    } 
  } catch (...) {
    // This might happen if a QString-to-datatype conversion fails
    // Just consider it a false match and ignore the exception
  }
  return false;
}
Example #21
0
VCSlider::VCSlider(QWidget* parent, Doc* doc) : VCWidget(parent, doc)
{
    /* Set the class name "VCSlider" as the object name as well */
    setObjectName(VCSlider::staticMetaObject.className());

    m_hbox = NULL;
    m_topLabel = NULL;
    m_slider = NULL;
    m_knob = NULL;
    m_bottomLabel = NULL;

    m_valueDisplayStyle = ExactValue;

    m_levelLowLimit = 0;
    m_levelHighLimit = UCHAR_MAX;

    m_levelValue = 0;
    m_levelValueChanged = false;

    m_playbackFunction = Function::invalidId();
    m_playbackValue = 0;
    m_playbackValueChanged = false;

    m_submasterValue = UCHAR_MAX;

    m_widgetMode = WSlider;

    setType(VCWidget::SliderWidget);
    setCaption(QString());
    setFrameStyle(KVCFrameStyleSunken);

    /* Main VBox */
    new QVBoxLayout(this);

    /* Top label */
    m_topLabel = new QLabel(this);
    m_topLabel->setAlignment(Qt::AlignHCenter);

    layout()->addWidget(m_topLabel);

    /* Slider's HBox |stretch|slider|stretch| */
    m_hbox = new QHBoxLayout();

    /* Put stretchable space before the slider (to its left side) */
    m_hbox->addStretch();

    /* The slider */
    m_slider = new ClickAndGoSlider(this);

    m_hbox->addWidget(m_slider);
    m_slider->setRange(0, 255);
    m_slider->setPageStep(1);
    m_slider->setInvertedAppearance(false);
    m_slider->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    m_slider->setMinimumWidth(32);
    m_slider->setMaximumWidth(80);
    m_slider->setStyleSheet(sliderStyleSheet);

    connect(m_slider, SIGNAL(valueChanged(int)),
            this, SLOT(slotSliderMoved(int)));
    m_externalMovement = false;

    /* Put stretchable space after the slider (to its right side) */
    m_hbox->addStretch();

    layout()->addItem(m_hbox);

    /* Click & Go button */
    m_cngType = ClickAndGoWidget::None;

    m_cngButton = new QToolButton(this);
    m_cngButton->setFixedSize(48, 48);
    m_cngButton->setIconSize(QSize(42, 42));
    m_menu = new QMenu(this);
    QWidgetAction* action = new QWidgetAction(this);
    m_cngWidget = new ClickAndGoWidget();
    action->setDefaultWidget(m_cngWidget);
    m_menu->addAction(action);
    m_cngButton->setMenu(m_menu);
    m_cngButton->setPopupMode(QToolButton::InstantPopup);
    layout()->addWidget(m_cngButton);
    layout()->setAlignment(m_cngButton, Qt::AlignHCenter);
    m_cngButton->hide();

    connect(m_cngWidget, SIGNAL(levelChanged(uchar)),
            this, SLOT(slotClickAndGoLevelChanged(uchar)));
    connect(m_cngWidget, SIGNAL(colorChanged(QRgb)),
            this, SLOT(slotClickAndGoColorChanged(QRgb)));
    connect(m_cngWidget, SIGNAL(levelAndPresetChanged(uchar,QImage)),
            this, SLOT(slotClickAndGoLevelAndPresetChanged(uchar, QImage)));

    /* Bottom label */
    m_bottomLabel = new QLabel(this);
    layout()->addWidget(m_bottomLabel);
    m_bottomLabel->setAlignment(Qt::AlignCenter);
    m_bottomLabel->setWordWrap(true);
    m_bottomLabel->hide();

    setMinimumSize(20, 20);
    QSettings settings;
    QVariant var = settings.value(SETTINGS_SLIDER_SIZE);
    if (var.isValid() == true)
        resize(var.toSize());
    else
        resize(VCSlider::defaultSize);

    /* Initialize to playback mode by default */
    setInvertedAppearance(false);
    setSliderMode(Playback);

    /* Update the slider according to current mode */
    slotModeChanged(mode());

    /* Listen to fixture removals so that LevelChannels can be removed when
       they no longer point to an existing fixture->channel */
    connect(m_doc, SIGNAL(fixtureRemoved(quint32)),
            this, SLOT(slotFixtureRemoved(quint32)));
}
void QQuickAnimatedImage::movieRequestFinished()
{
    Q_D(QQuickAnimatedImage);

    if (d->reply) {
        d->redirectCount++;
        if (d->redirectCount < ANIMATEDIMAGE_MAXIMUM_REDIRECT_RECURSION) {
            QVariant redirect = d->reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
            if (redirect.isValid()) {
                QUrl url = d->reply->url().resolved(redirect.toUrl());
                d->reply->deleteLater();
                setSource(url);
                return;
            }
        }

        d->redirectCount=0;
        d->_movie = new QMovie(d->reply);
    }

    if (!d->_movie->isValid()) {
        qmlInfo(this) << "Error Reading Animated Image File " << d->url.toString();
        delete d->_movie;
        d->_movie = 0;
        d->setImage(QImage());
        if (d->progress != 0) {
            d->progress = 0;
            emit progressChanged(d->progress);
        }
        d->status = Error;
        emit statusChanged(d->status);

        if (sourceSize() != d->oldSourceSize) {
            d->oldSourceSize = sourceSize();
            emit sourceSizeChanged();
        }
        if (isPlaying() != d->oldPlaying)
            emit playingChanged();
        return;
    }

    connect(d->_movie, SIGNAL(stateChanged(QMovie::MovieState)),
            this, SLOT(playingStatusChanged()));
    connect(d->_movie, SIGNAL(frameChanged(int)),
            this, SLOT(movieUpdate()));
    d->_movie->setCacheMode(QMovie::CacheAll);

    d->status = Ready;
    emit statusChanged(d->status);

    if (d->progress != 1.0) {
        d->progress = 1.0;
        emit progressChanged(d->progress);
    }

    bool pausedAtStart = d->paused;
    if (d->playing) {
        d->_movie->start();
    }
    if (pausedAtStart)
        d->_movie->setPaused(true);
    if (d->paused || !d->playing) {
        d->_movie->jumpToFrame(d->preset_currentframe);
        d->preset_currentframe = 0;
    }
    d->setImage(d->_movie->currentPixmap().toImage());

    if (isPlaying() != d->oldPlaying)
        emit playingChanged();
    if (sourceSize() != d->oldSourceSize) {
        d->oldSourceSize = sourceSize();
        emit sourceSizeChanged();
    }
}
Example #23
0
// Apply a simple variant type to a DOM property
static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop)
{
    switch (v.type()) {
    case QVariant::String: {
        DomString *str = new DomString();
        str->setText(v.toString());
        if (!translateString)
            str->setAttributeNotr(QLatin1String("true"));
        dom_prop->setElementString(str);
    }
    return true;

    case QVariant::ByteArray:
        dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray()));
        return true;

    case QVariant::Int:
        dom_prop->setElementNumber(v.toInt());
        return true;

    case QVariant::UInt:
        dom_prop->setElementUInt(v.toUInt());
        return true;

    case QVariant::LongLong:
        dom_prop->setElementLongLong(v.toLongLong());
        return true;

    case QVariant::ULongLong:
        dom_prop->setElementULongLong(v.toULongLong());
        return true;

    case QVariant::Double:
        dom_prop->setElementDouble(v.toDouble());
        return true;

    case QVariant::Bool:
        dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue);
        return true;

    case QVariant::Char: {
        DomChar *ch = new DomChar();
        const QChar character = v.toChar();
        ch->setElementUnicode(character.unicode());
        dom_prop->setElementChar(ch);
    }
    return true;

    case QVariant::Point: {
        DomPoint *pt = new DomPoint();
        const QPoint point = v.toPoint();
        pt->setElementX(point.x());
        pt->setElementY(point.y());
        dom_prop->setElementPoint(pt);
    }
    return true;

    case QVariant::PointF: {
        DomPointF *ptf = new DomPointF();
        const QPointF pointf = v.toPointF();
        ptf->setElementX(pointf.x());
        ptf->setElementY(pointf.y());
        dom_prop->setElementPointF(ptf);
    }
    return true;

    case QVariant::Color: {
        DomColor *clr = new DomColor();
        const QColor color = qvariant_cast<QColor>(v);
        clr->setElementRed(color.red());
        clr->setElementGreen(color.green());
        clr->setElementBlue(color.blue());
        const int alphaChannel = color.alpha();
        if (alphaChannel != 255)
            clr->setAttributeAlpha(alphaChannel);
        dom_prop->setElementColor(clr);
    }
    return true;

    case QVariant::Size: {
        DomSize *sz = new DomSize();
        const QSize size = v.toSize();
        sz->setElementWidth(size.width());
        sz->setElementHeight(size.height());
        dom_prop->setElementSize(sz);
    }
    return true;

    case QVariant::SizeF: {
        DomSizeF *szf = new DomSizeF();
        const QSizeF sizef = v.toSizeF();
        szf->setElementWidth(sizef.width());
        szf->setElementHeight(sizef.height());
        dom_prop->setElementSizeF(szf);
    }
    return true;

    case QVariant::Rect: {
        DomRect *rc = new DomRect();
        const QRect rect = v.toRect();
        rc->setElementX(rect.x());
        rc->setElementY(rect.y());
        rc->setElementWidth(rect.width());
        rc->setElementHeight(rect.height());
        dom_prop->setElementRect(rc);
    }
    return true;

    case QVariant::RectF: {
        DomRectF *rcf = new DomRectF();
        const QRectF rectf = v.toRectF();
        rcf->setElementX(rectf.x());
        rcf->setElementY(rectf.y());
        rcf->setElementWidth(rectf.width());
        rcf->setElementHeight(rectf.height());
        dom_prop->setElementRectF(rcf);
    }
    return true;

    case QVariant::Font: {
        DomFont *fnt = new DomFont();
        const QFont font = qvariant_cast<QFont>(v);
        const uint mask = font.resolve();
        if (mask & QFont::WeightResolved) {
            fnt->setElementBold(font.bold());
            fnt->setElementWeight(font.weight());
        }
        if (mask & QFont::FamilyResolved)
            fnt->setElementFamily(font.family());
        if (mask & QFont::StyleResolved)
            fnt->setElementItalic(font.italic());
        if (mask & QFont::SizeResolved)
            fnt->setElementPointSize(font.pointSize());
        if (mask & QFont::StrikeOutResolved)
            fnt->setElementStrikeOut(font.strikeOut());
        if (mask & QFont::UnderlineResolved)
            fnt->setElementUnderline(font.underline());
        if (mask & QFont::KerningResolved)
            fnt->setElementKerning(font.kerning());
        if (mask & QFont::StyleStrategyResolved) {
            const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy");
            fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy())));
        }
        dom_prop->setElementFont(fnt);
    }
    return true;

#ifndef QT_NO_CURSOR
    case QVariant::Cursor: {
        const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape");
        dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape())));
    }
    return true;
#endif

    case QVariant::KeySequence: {
        DomString *s = new DomString();
        s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText));
        dom_prop->setElementString(s);
    }
    return true;

    case QVariant::Locale: {
        DomLocale *dom = new DomLocale();
        const QLocale locale = qvariant_cast<QLocale>(v);

        const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language");
        const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country");

        dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language())));
        dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country())));

        dom_prop->setElementLocale(dom);
    }
    return true;

    case QVariant::SizePolicy: {
        DomSizePolicy *dom = new DomSizePolicy();
        const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v);

        dom->setElementHorStretch(sizePolicy.horizontalStretch());
        dom->setElementVerStretch(sizePolicy.verticalStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy())));
        dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy())));

        dom_prop->setElementSizePolicy(dom);
    }
    return true;

    case QVariant::Date: {
        DomDate *dom = new DomDate();
        const QDate date = qvariant_cast<QDate>(v);

        dom->setElementYear(date.year());
        dom->setElementMonth(date.month());
        dom->setElementDay(date.day());

        dom_prop->setElementDate(dom);
    }
    return true;

    case QVariant::Time: {
        DomTime *dom = new DomTime();
        const QTime time = qvariant_cast<QTime>(v);

        dom->setElementHour(time.hour());
        dom->setElementMinute(time.minute());
        dom->setElementSecond(time.second());

        dom_prop->setElementTime(dom);
    }
    return true;

    case QVariant::DateTime: {
        DomDateTime *dom = new DomDateTime();
        const QDateTime dateTime = qvariant_cast<QDateTime>(v);

        dom->setElementHour(dateTime.time().hour());
        dom->setElementMinute(dateTime.time().minute());
        dom->setElementSecond(dateTime.time().second());
        dom->setElementYear(dateTime.date().year());
        dom->setElementMonth(dateTime.date().month());
        dom->setElementDay(dateTime.date().day());

        dom_prop->setElementDateTime(dom);
    }
    return true;

    case QVariant::Url: {
        DomUrl *dom = new DomUrl();
        const QUrl url = v.toUrl();

        DomString *str = new DomString();
        str->setText(url.toString());
        dom->setElementString(str);

        dom_prop->setElementUrl(dom);
    }
    return true;

    case QVariant::StringList: {
        DomStringList *sl = new DomStringList;
        sl->setElementString(qvariant_cast<QStringList>(v));
        dom_prop->setElementStringList(sl);
    }
    return true;

    default:
        break;
    }

    return false;
}
void docAttach::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  //source type from document widget
  param = pParams.value("sourceType", &valid);
  if (valid)
    _sourcetype = param.toString();

  //source id from document widget
  param = pParams.value("source_id", &valid);
  if (valid)
    _sourceid = param.toInt();

  // Only urls are editable
  param = pParams.value("url_id", &valid);
  if(valid)
  {
    if (DEBUG) qDebug() << "got url_id" << param;
    XSqlQuery qry;
    _urlid = param.toInt();
    qry.prepare("SELECT url_source, url_source_id, url_title, url_url, url_stream "
                "  FROM url"
                " WHERE (url_id=:url_id);" );
    qry.bindValue(":url_id", _urlid);
    qry.exec();
    if(qry.first())
    {
      setWindowTitle(tr("Edit Attachment Link"));
      QUrl url(qry.value("url_url").toString());
      if (url.scheme().isEmpty())
        url.setScheme("file");

      if (DEBUG) qDebug() << qry.value("url_url") << "converted to" << url;

      _url->setText(url.toString());
      if (url.scheme() == "file")
      {
        if (DEBUG)
          qDebug() << "file title:"    << qry.value("url_title").toString()
                   << " text:"         << url.toString()
                   << "stream length:" << qry.value("url_stream").toString().length();
        _docType->setId(-2);
        _filetitle->setText(qry.value("url_title").toString());
        _file->setText(url.toString());
        if (qry.value("url_stream").toString().length())
        {
          _fileList->setEnabled(false);
          _file->setEnabled(false);
          _saveDbCheck->setEnabled(false);
        }
      }
      else
      {
        if (DEBUG)
          qDebug() << "! file title:" << qry.value("url_title").toString()
                   << " text:" << url.toString();
        _docType->setId(-3);
        _urltitle->setText(qry.value("url_title").toString());
        _url->setText(url.toString());
      }
      _mode = "edit";
      _docType->setEnabled(false);
    }
    ErrorReporter::error(QtCriticalMsg, 0, tr("Error URL"),
                         qry, __FILE__, __LINE__);
  }
}
Example #25
0
bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value,
		int role)
{
	bool success = false;

	if (role == RemuxEntryRole::NewPathsToProcessRole) {
		QStringList pathList = value.toStringList();

		if (pathList.size() == 0) {
			if (index.row() < queue.size()) {
				beginRemoveRows(QModelIndex(), index.row(),
						index.row());
				queue.removeAt(index.row());
				endRemoveRows();
			}
		} else {
			if (pathList.size() > 1 && index.row() < queue.length()) {
				queue[index.row()].sourcePath = pathList[0];
				checkInputPath(index.row());

				pathList.removeAt(0);

				success = true;
			}

			if (pathList.size() > 0) {
				int row = index.row();
				int lastRow = row + pathList.size() - 1;
				beginInsertRows(QModelIndex(), row, lastRow);

				for (QString path : pathList) {
					RemuxQueueEntry entry;
					entry.sourcePath = path;

					queue.insert(row, entry);
					row++;
				}
				endInsertRows();

				for (row = index.row(); row <= lastRow; row++) {
					checkInputPath(row);
				}

				success = true;
			}
		}
	} else if (index.row() == queue.length()) {
		QString path = value.toString();

		if (!path.isEmpty()) {
			RemuxQueueEntry entry;
			entry.sourcePath = path;

			beginInsertRows(QModelIndex(), queue.length() + 1,
				queue.length() + 1);
			queue.append(entry);
			endInsertRows();

			checkInputPath(index.row());
			success = true;
		}
	} else {
		QString path = value.toString();

		if (path.isEmpty()) {
			if (index.column() == RemuxEntryColumn::InputPath) {
				beginRemoveRows(QModelIndex(), index.row(),
						index.row());
				queue.removeAt(index.row());
				endRemoveRows();
			}
		} else {
			switch (index.column()) {
			case RemuxEntryColumn::InputPath:
				queue[index.row()].sourcePath = value.toString();
				checkInputPath(index.row());
				success = true;
				break;
			case RemuxEntryColumn::OutputPath:
				queue[index.row()].targetPath = value.toString();
				emit dataChanged(index, index);
				success = true;
				break;
			}
		}
	}

	return success;
}
void LYGithubManager::onIssuesReturned(){

	QList<QByteArray> headerList = getIssuesReply_->rawHeaderList();
	for(int x = 0; x < headerList.count(); x++){
		if(headerList.at(x) == "Link" && lastPageNumber_ == -1){
			QString linkHeader = getIssuesReply_->rawHeader(headerList.at(x));
			int lastPageNumber = -1;
			int nextPageNumber = -1;
			QStringList linkHeaderItems = linkHeader.split(',');
			for(int y = 0; y < linkHeaderItems.count(); y++){
				if(linkHeaderItems.at(y).contains("; rel=\"last\""))
					lastPageNumber = pageNumberFromURLString(linkHeaderItems.at(y));
				if(linkHeaderItems.at(y).contains("; rel=\"next\""))
					nextPageNumber = pageNumberFromURLString(linkHeaderItems.at(y));
			}

			lastPageNumber_ = lastPageNumber;
		}
	}

	int currentPageNumber = -1;
	if(lastPageNumber_ != -1)
		currentPageNumber = pageNumberFromURLString(lastGetIssuesRequest_);

	QJson::Parser parser;
	QVariant githubFullReply = parser.parse(getIssuesReply_->readAll());
	bool doEmit = false;
	QList<QVariantMap> localRetVal;
	QVariantMap oneIssue;
	if(githubFullReply.canConvert(QVariant::List)){
		QVariantList githubListReply = githubFullReply.toList();
		if(githubListReply.at(0).canConvert(QVariant::Map)){
			if((lastPageNumber_ == -1) || (currentPageNumber == lastPageNumber_) )
				doEmit = true;
			for(int x = 0; x < githubListReply.count(); x++){
				oneIssue = githubListReply.at(x).toMap();
				localRetVal.append(oneIssue);
			}
		}
	}

	fullIssuesReply_.append(localRetVal);

	disconnect(getIssuesReply_, 0);
	getIssuesReply_->deleteLater();
	getIssuesReply_ = 0;

	if((lastPageNumber_ != -1) && (currentPageNumber != lastPageNumber_)){

		QNetworkRequest request;

		QString currentPageNumberString = QString("&page=%1").arg(currentPageNumber);
		QString nextPageNumberString = QString("&page=%1").arg(currentPageNumber+1);
		lastGetIssuesRequest_.replace(currentPageNumberString, nextPageNumberString);
		request.setUrl(QUrl(lastGetIssuesRequest_));

		QString userInfo = userName_+":"+password_;
		QByteArray userData = userInfo.toLocal8Bit().toBase64();
		QString headerData = "Basic " + userData;
		request.setRawHeader("Authorization", headerData.toLocal8Bit());

		LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage(QString("Processed page %1 of %2 for getIssues request").arg(currentPageNumber).arg(lastPageNumber_));

		getIssuesReply_ = manager_->get(request);
		connect(getIssuesReply_, SIGNAL(readyRead()), this, SLOT(onIssuesReturned()));
		return;
	}

	if(doEmit){
		LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Processed final getIssues request");

		lastPageNumber_ = -1;
		emit issuesReturned(fullIssuesReply_);
		return;
	}
	LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Something went wrong in getIssues request");
}
Example #27
0
AttributeAccessDlg::AttributeAccessDlg( const QString& title, RTT::SDK::IAttributeAccessPtr attrAccess, RTT::SDK::IObjectFactoryPtr pObjFactory )
: m_attrAccess( attrAccess )
, m_pObjFactory( pObjFactory )
{
	setWindowTitle( title );
	resize( 600, 500);
	using namespace RTT::SDK;
	QVBoxLayout *layout = new QVBoxLayout();
	m_tree = new QTreeWidget();

	m_openAttrAccessDlg = new QPushButton("Attribute Access");
	m_openMetaDataDlg = new QPushButton("Metadata");

	QStringList headerLabels;

	headerLabels.push_back(QString("Name"));
	headerLabels.push_back(QString("Value"));
	headerLabels.push_back(QString("Type"));

	m_tree->setHeaderLabels(headerLabels);

	IObjectEnumerationPtr names = attrAccess->GetAttributeNames();
	if ( names.isEmpty() )
	{
		return;
	}
	for (size_t i=0; i<names->GetItemCount(); ++i)
	{
		RTT::SDK::IStringPtr name = rtt::commons::dynamic_ptr_cast<RTT::SDK::IString>( names->GetItem(i)->QueryInterface( RTT::SDK::IID_IString ) );
		DispVariant valVar = attrAccess->GetAttributeValue(name);
		QStringList columns;
		columns.push_back(RTT_SDK_UTF8(name));
		try
		{
			if ( valVar.m_type == RTT::SDK::DispVariant::TP_IUNKNOWN )
			{
				RTT::SDK::IVariantListPtr list = RTT::SDK::interface_cast<RTT::SDK::IVariantList>(valVar.m_pIUnknown);
				if ( !list.isEmpty() )
				{
					QString text;
					size_t numItems = list->GetItemCount();
					for( size_t n = 0; n<numItems; n++ )
					{
						DispVariant itemVal = list->GetItem( n );
						text += QString("%1;").arg(rttDispTypeConversion(itemVal).toCString());
					}
					columns.push_back( text );
				}
				else
				{
					columns.push_back("Unknown type");
				}
			}
			else
			{
				switch(valVar.m_type)
				{
				case DispVariant::TP_FLOAT2:
					{
						RTT::SDK::FVec2 v2 = rttDispTypeConversion(valVar);
						columns.push_back(QString("[%1,%2]").arg(v2[0]).arg(v2[1]));
					}
				case DispVariant::TP_FLOAT3:
					{
						RTT::SDK::FVec3 v3 = rttDispTypeConversion(valVar);
						columns.push_back(QString("[%1,%2,%3]").arg(v3[0]).arg(v3[1]).arg(v3[2]));
					}
				case DispVariant::TP_FLOAT4:
					{
						RTT::SDK::FVec4 v4 = rttDispTypeConversion(valVar);
						columns.push_back(QString("[%1,%2,%3,%4]").arg(v4[0]).arg(v4[1]).arg(v4[2]).arg(v4[3]));
					}
				default:
					columns.push_back(rttDispTypeConversion(valVar).toCString());
				}
			}
		}
		catch(...)
		{
			columns.push_back("Invalid type");
		}
		columns.push_back( typeNames[valVar.m_type] );

		QTreeWidgetItem* pItem = new QTreeWidgetItem((QTreeWidget*)0, columns);
		QVariant var;
		try
		{
			var.setValue(rttDispTypeConversion(valVar).toIUnknown());
		}
		catch(...)
		{
			var.setValue(IUnknownPtr());
		}
		pItem->setData(0,Qt::UserRole,var);
		RTT::SDK::DispVariant::Type valueType = RTT::SDK::rttDispTypeConversion( valVar ).getType();
		if( valueType == RTT::SDK::DispVariant::TP_FLOAT ||
			valueType == RTT::SDK::DispVariant::TP_DOUBLE ||
			valueType == RTT::SDK::DispVariant::TP_LONG ||
			valueType == RTT::SDK::DispVariant::TP_ULONG ||
			valueType == RTT::SDK::DispVariant::TP_BOOL )
		{
			pItem->setFlags(pItem->flags() | Qt::ItemIsEditable);
		}
		m_tree->addTopLevelItem(pItem);
	}

	m_tree->header()->resizeSection(0,300);
	m_tree->header()->resizeSection(2,60);

	layout->addWidget(m_tree);
	layout->addWidget(m_openAttrAccessDlg);
	layout->addWidget( m_openMetaDataDlg);

	QObject::connect(m_openAttrAccessDlg , SIGNAL(clicked(bool)), this, SLOT(onAttributeAccessClicked()));
	QObject::connect(m_openMetaDataDlg , SIGNAL(clicked(bool)), this, SLOT(onMetaDataAccessClicked()));
	QObject::connect(m_tree , SIGNAL(itemChanged(QTreeWidgetItem*,int)), this, SLOT(onItemEdited(QTreeWidgetItem*,int)));

	setLayout(layout);
}
Example #28
0
QVariant Id::toVariant() const
{
	QVariant result;
	result.setValue(*this);
	return result;
}
Example #29
0
void vendor::set(const ParameterList &pParams)
{
  QVariant param;
  bool     valid;

  param = pParams.value("crmacct_number", &valid);
  if (valid)
    _number->setText(param.toString());

  param = pParams.value("crmacct_name", &valid);
  if (valid)
    _name->setText(param.toString());

  param = pParams.value("crmacct_id", &valid);
  if (valid)
    _crmacctid = param.toInt();

  param = pParams.value("vend_id", &valid);
  if (valid)
  {
    _vendid = param.toInt();
    populate();
  }

  param = pParams.value("mode", &valid);
  if (valid)
  {
    if (param.toString() == "new")
    {
      _mode = cNew;

      q.exec("SELECT NEXTVAL('vend_vend_id_seq') AS vend_id;");
      if (q.first())
        _vendid = q.value("vend_id").toInt();
      else
        systemError(this, tr("A System Error occurred at %1::%2.")
                          .arg(__FILE__)
                          .arg(__LINE__) );

      _comments->setId(_vendid);
      _defaultShipVia->setText(_metrics->value("DefaultPOShipVia"));
  
      connect(_number, SIGNAL(lostFocus()), this, SLOT(sCheck()));

      if (_privleges->check("MaintainVendorAddresses"))
      {
        connect(_vendaddr, SIGNAL(valid(bool)), _editAddress, SLOT(setEnabled(bool)));
        connect(_vendaddr, SIGNAL(valid(bool)), _deleteAddress, SLOT(setEnabled(bool)));
        connect(_vendaddr, SIGNAL(itemSelected(int)), _editAddress, SLOT(animateClick()));
      }
      else
      {
        _newAddress->setEnabled(FALSE);
        connect(_vendaddr, SIGNAL(itemSelected(int)), _viewAddress, SLOT(animateClick()));
      }

      _number->setFocus();
    }
    else if (param.toString() == "edit")
    {
      _mode = cEdit;

      if (_privleges->check("MaintainVendorAddresses"))
      {
        connect(_vendaddr, SIGNAL(valid(bool)), _editAddress, SLOT(setEnabled(bool)));
        connect(_vendaddr, SIGNAL(valid(bool)), _deleteAddress, SLOT(setEnabled(bool)));
        connect(_vendaddr, SIGNAL(itemSelected(int)), _editAddress, SLOT(animateClick()));
      }
      else
      {
        _newAddress->setEnabled(FALSE);
        connect(_vendaddr, SIGNAL(itemSelected(int)), _viewAddress, SLOT(animateClick()));
      }

      _save->setFocus();
    }
    else if (param.toString() == "view")
    {
      _mode = cView;

      _number->setEnabled(FALSE);
      _vendtype->setEnabled(FALSE);
      _active->setEnabled(FALSE);
      _name->setEnabled(FALSE);
      _accountNumber->setEnabled(FALSE);
      _defaultTerms->setEnabled(FALSE);
      _defaultShipVia->setEnabled(FALSE);
      _defaultCurr->setEnabled(FALSE);
      _contact1->setEnabled(FALSE);
      _contact2->setEnabled(FALSE);
      _address->setEnabled(FALSE);
      _notes->setReadOnly(FALSE);
      _poComments->setReadOnly(TRUE);
      _poItems->setEnabled(FALSE);
      _restrictToItemSource->setEnabled(FALSE);
      _receives1099->setEnabled(FALSE);
      _qualified->setEnabled(FALSE);
      _emailPODelivery->setEnabled(FALSE);
      _emailPOGroup->setEnabled(FALSE);
      _newAddress->setEnabled(FALSE);
      _defaultFOBGroup->setEnabled(false);
      _taxauth->setEnabled(false);
      _match->setEnabled(false);
      _newTaxreg->setEnabled(false);
      _comments->setReadOnly(TRUE);
      _save->hide();
      _close->setText(tr("&Close"));

      disconnect(_taxreg, SIGNAL(valid(bool)), _deleteTaxreg, SLOT(setEnabled(bool)));
      disconnect(_taxreg, SIGNAL(valid(bool)), _editTaxreg, SLOT(setEnabled(bool)));
      disconnect(_taxreg, SIGNAL(itemSelected(int)), _editTaxreg, SLOT(animateClick()));
      connect(_taxreg, SIGNAL(itemSelected(int)), _viewTaxreg, SLOT(animateClick()));

      _close->setFocus();
    }
  }

  if(cNew == _mode || !pParams.inList("showNextPrev"))
  {
    _next->hide();
    _previous->hide();
  }
}
Example #30
0
bool ParameterFileModel::setData(
		const QModelIndex& ind, const QVariant& value, int role) {

	if (!prefixValid())
		return false;

	switch (role) {
	case Qt::EditRole:
	case Qt::DisplayRole:
		if ((ind.row() >= 0) && (ind.row() < _keys.size())) {
			switch (ind.column()) {
			case 0:
				if (_onlyParams)
					return false;

				if (value.canConvert(QVariant::String)) {
					QString oldName = _keys[ind.row()];
					QString newName;
					// do not forget the prefix at the beginning of the name
					if (!_prefix.isEmpty())
						newName = _prefix + ".";
					newName += value.toString();
					if (oldName == newName)
						return true; // nothing to do
					if (_parameterFile->isSet(newName))
						return false; // don't overwrite existing value

					// save value
					QString val = getValue(oldName);
					erase(oldName);
					setValue(newName, val);
					emit dataChanged(ind, ind);
					return true;
				}
				break;
			case 1:
				if (value.canConvert(QVariant::String)) {
					QString valueStr = value.toString();
					QString keyStr = _keys[ind.row()];
					if (valueStr == getValue(keyStr))
						return true; // nothing to do

					setValue(keyStr, valueStr);
					if (_onlyParams && _metaInfos->isDynamic(getClass(keyStr))) {
						save();
						_updateDynamics();
						QTimer::singleShot(0, this, SLOT(_update()));
						emit dynamicUpdate();
					}
					emit dataChanged(index(ind.row(), 0), ind);
					return true;
				}
				break;
			case 2:
				if (value.canConvert(QVariant::Int)) {
					// check if value is allowed
					int valueInt = value.toInt();
					QString valueStr = QVariant(valueInt).toString();
					if (valueInt < 0 || valueInt > 3) {
						return false;
					}

					if (valueInt == 0) {
						// 0 is default value -> no entry needed
						if (isSet(_keys[ind.row()] + ".editorpriority")) {
							// check if value exists to prevent exceptions
							erase(_keys[ind.row()] + ".editorpriority");
							emit dataChanged(index(ind.row(), 0), ind);
						}
						return true;
					}

					if (valueStr ==
							getValue(_keys[ind.row()] + ".editorpriority")) {
						return true; // nothing to do
					}

					setValue(_keys[ind.row()] + ".editorpriority", valueStr);
					emit dataChanged(index(ind.row(), 0), ind);
					return true;
				}
				break;
			}
		}
		break;

	case Qt::CheckStateRole:
		if (_useMetaInfo && ind.column()==1 && isParameter(_keys[ind.row()])) {
			Q_ASSERT(getType(_keys[ind.row()]) == "bool");
			bool checked (value.toBool());
			setValue (_keys[ind.row()], checked ? "true" : "false");
            emit dataChanged(index(ind.row(),0),ind);
            if (_keys[ind.row()].contains("active") && checked == true){
                reactivatePreviousPlugins();
            }
            // additional check whether the changed Parameter is the ActiveInactive
            if (_keys[ind.row()].contains("active") && checked == false){
                deactivate();
            }
        }
		break;
	}
	return false;
}