void evaluation()
    {
      QFETCH( QString, string );
      QFETCH( bool, evalError );
      QFETCH( QVariant, result );

      QgsExpression exp( string );
      QCOMPARE( exp.hasParserError(), false );
      if ( exp.hasParserError() )
        qDebug() << exp.parserErrorString();

      QVariant res = exp.evaluate();
      if ( exp.hasEvalError() )
        qDebug() << exp.evalErrorString();
      if ( res.type() != result.type() )
      {
        qDebug() << "got " << res.typeName() << " instead of " << result.typeName();
      }
      //qDebug() << res.type() << " " << result.type();
      //qDebug() << "type " << res.typeName();
      QCOMPARE( exp.hasEvalError(), evalError );

      QCOMPARE( res.type(), result.type() );
      switch ( res.type() )
      {
        case QVariant::Invalid:
          break; // nothing more to check
        case QVariant::Int:
          QCOMPARE( res.toInt(), result.toInt() );
          break;
        case QVariant::Double:
          QCOMPARE( res.toDouble(), result.toDouble() );
          break;
        case QVariant::String:
          QCOMPARE( res.toString(), result.toString() );
          break;
        case QVariant::Date:
          QCOMPARE( res.toDate(), result.toDate() );
          break;
        case QVariant::DateTime:
          QCOMPARE( res.toDateTime(), result.toDateTime() );
          break;
        case QVariant::Time:
          QCOMPARE( res.toTime(), result.toTime() );
          break;
        case QVariant::UserType:
        {
          if ( res.userType() == qMetaTypeId<QgsExpression::Interval>() )
          {
            QgsExpression::Interval inter = res.value<QgsExpression::Interval>();
            QgsExpression::Interval gotinter = result.value<QgsExpression::Interval>();
            QCOMPARE( inter.seconds(), gotinter.seconds() );
          }
          else
          {
            QFAIL( "unexpected user type" );
          }
          break;
        }
        default:
          Q_ASSERT( false ); // should never happen
      }
    }
Example #2
0
void ParameterEdit::editItem()
{
    if(_table->currentSelection() != -1) {
	bool do_update = false;
	int r = _table->currentRow();
	Q3CheckTableItem * ctItem = (Q3CheckTableItem*)_table->item(r, 0);
        if(ctItem == 0)
          return;
	bool active = ctItem->isChecked();
	QString name = _table->text(r, 1);
	QVariant var = _params[name];
	BoolEdit * be = 0;
	IntEdit * ie = 0;
	DoubleEdit * de = 0;
	StringEdit * se = 0;
	ListEdit * le = 0;
	switch(var.type()) {
	case QVariant::Bool:
	    be = new BoolEdit(this);
	    be->_name->setText(name);
	    be->_active->setChecked(active);
	    be->setValue(var.toBool());
	    if(be->exec() == QDialog::Accepted) {
		var = QVariant(be->value(), 0);
		active = be->_active->isChecked();
		do_update = TRUE;
	    }
	    delete be;
	    be = 0;
	    break;
	case QVariant::Int:
	    ie = new IntEdit(this);
	    ie->_name->setText(name);
	    ie->_active->setChecked(active);
	    ie->_value->setText(QString::number(var.toInt()));
	    if(ie->exec() == QDialog::Accepted) {
		var = QVariant(ie->_value->text().toInt());
		active = ie->_active->isChecked();
		do_update = TRUE;
	    }
	    delete ie;
	    ie = 0;
	    break;
	case QVariant::Double:
	    de = new DoubleEdit(this);
	    de->_name->setText(name);
	    de->_active->setChecked(active);
	    de->_value->setText(QString::number(var.toDouble()));
	    if(de->exec() == QDialog::Accepted) {
		var = QVariant(de->_value->text().toDouble());
		active = de->_active->isChecked();
		do_update = TRUE;
	    }
	    delete de;
	    de = 0;
	    break;
	case QVariant::String:
	    se = new StringEdit(this);
	    se->_name->setText(name);
	    se->_active->setChecked(active);
	    se->_value->setText(var.toString());
	    if(se->exec() == QDialog::Accepted) {
		var = QVariant(se->_value->text());
		active = se->_active->isChecked();
		do_update = TRUE;
	    }
	    delete se;
	    se = 0;
	    break;
	case QVariant::List:
	    le = new ListEdit(this);
	    le->_name->setText(name);
	    le->_active->setChecked(active);
	    le->setList(var.toList());
	    if(le->exec() == QDialog::Accepted) {
		var = QVariant(le->list());
		active = le->_active->isChecked();
		do_update = TRUE;
	    }
	    delete le;
	    le = 0;
	    break;
	default:
	    QMessageBox::warning(this, tr("Warning"), QString(tr("I do not know how to edit QVariant type %1.")).arg(var.typeName()));
	};
		
	if(do_update) {
	    _params[name] = var;
	    ctItem->setChecked(active);
	    _table->setText(r, 1, name);
	    _table->setText(r, 2, var.typeName());
	    _table->setText(r, 3, var.toString());
	}
    }
}
Example #3
0
void GroupDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    QRect r = option.rect;
    QFont font = painter->font();
    QPen pen = painter->pen();

    if (!index.parent().isValid())
    {
        painter->setBrush(Qt::red);
        font.setPixelSize(14);
        font.setUnderline(false);
        painter->setFont(font);
        pen.setColor(grayFont);

        //painter->setBackground(Qt::gray);
        painter->fillRect(option.rect, grayBackground);
        if (index.column()==0)
        {
            //if (option.state & QStyle::State_Editing)
            QPixmap icon = tree->isExpanded(index)
                    ? QPixmap(":/Images/Visitors/icon_minus.png")
                    : QPixmap(":/Images/Visitors/icon_plus.png");
                painter->drawPixmap(r.x() + 8, r.y() + 6, 16, 16, icon);

        }        
        painter->setPen(pen);
        painter->setFont(font);
        painter->drawText(QPoint(r.x() + 32, r.y() + 18), index.data().toString());
    }
    else
    {
        if (option.state & QStyle::State_MouseOver)
        {
            painter->fillRect(option.rect, grayBackground);
        }
        QVariant value = index.data(Qt::DecorationRole);
        int adjust = index.column()==0 ? 24 : 0;
        if (value.isValid() && value.type() == QVariant::Icon)
        {
            QIcon icon = value.value<QIcon>();
            if (icon.availableSizes().count()>0)
            {
                int width = icon.availableSizes().at(0).width();
                icon.paint(painter, r.x()+8 + adjust, r.y(), width, 28);
                adjust += width + 8;
            }
        }

        font.setPixelSize(12);
        if (index.column() == 0 || index.column() == 10)
        {
            font.setUnderline(true);
            pen.setColor(hyperlink);
        }
        else
        {
            font.setUnderline(false);
            pen.setColor(grayFont);
        }
        painter->setPen(pen);
        painter->setFont(font);
        QTextOption textOptions(Qt::AlignLeft);
        textOptions.setWrapMode(QTextOption::NoWrap);
        painter->drawText(r.adjusted(8 + adjust,6,0,0), index.data().toString(), textOptions);
        //painter->drawText(QPoint(r.x() + 32, r.y() + r.height()/2 + font.pixelSize()/2 - 1), index.data().toString(), o);
    }
}
Example #4
0
void SettingsDialog::outputSettings() {
    QSettings settings;

    QListIterator<QString> itr(settings.allKeys());
    QString output;

    output += "QOwnNotes Debug Information\n";
    output += "===========================\n";

    QDateTime dateTime = QDateTime::currentDateTime();

    // add information about QOwnNotes
    output += "\n## General Info\n\n";
    output += prepareDebugInformationLine("Current Date", dateTime.toString());
    output += prepareDebugInformationLine("Version", QString(VERSION));
    output += prepareDebugInformationLine("Build date", QString(__DATE__));
    output += prepareDebugInformationLine("Build number",
                                          QString::number(BUILD));
    output += prepareDebugInformationLine("Platform", QString(PLATFORM));

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    output += prepareDebugInformationLine("Operating System",
                                          QSysInfo::prettyProductName());
    output += prepareDebugInformationLine("Build architecture",
                                          QSysInfo::buildCpuArchitecture());
    output += prepareDebugInformationLine("Current architecture",
                                          QSysInfo::currentCpuArchitecture());
#endif
    output += prepareDebugInformationLine("Release", QString(RELEASE));
    output += prepareDebugInformationLine("Qt Version", QT_VERSION_STR);

    // add information about the server
    output += "\n## Server Info\n\n";
    output += prepareDebugInformationLine("serverUrl",
                                          ui->serverUrlEdit->text());
    output += prepareDebugInformationLine("appIsValid",
                                          QString(appIsValid ? "yes" : "no"));
    if (appIsValid) {
        output += prepareDebugInformationLine("serverVersion", serverVersion);
        output += prepareDebugInformationLine("appVersion", appVersion);
    } else {
        output += prepareDebugInformationLine("connectionErrorMessage",
                                              connectionErrorMessage);
    }

    // add information about the settings
    output += "\n## Settings\n\n";

    // hide values of these keys
    QStringList keyHiddenList = (QStringList() << "cryptoKey" <<
                                 "ownCloud/password");

    while (itr.hasNext()) {
        QString key = itr.next();
        QVariant value = settings.value(key);

        // hide values of certain keys
        if (keyHiddenList.contains(key)) {
            output += prepareDebugInformationLine(key, "<hidden>");
        } else {
            switch (value.type()) {
                case QVariant::StringList:
                    output += prepareDebugInformationLine(
                            key,
                            value.toStringList().join(", "));
                    break;
                case QVariant::ByteArray:
                    output += prepareDebugInformationLine(key, "<binary data>");
                    break;
                default:
                    output += prepareDebugInformationLine(key,
                                                          value.toString());
            }
        }
    }

    ui->debugInfoTextEdit->setPlainText(output);
}
Example #5
0
void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    DWORD type;
    QByteArray regValueBuff;

    // Determine the type
    switch (value.type()) {
    case QVariant::List:
    case QVariant::StringList: {
        // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
        // native registry string list type. Otherwise we use REG_BINARY.
        type = REG_MULTI_SZ;
        QStringList l = variantListToStringList(value.toList());
        QStringList::const_iterator it = l.constBegin();
        for (; it != l.constEnd(); ++it) {
            if ((*it).length() == 0 || stringContainsNullChar(*it)) {
                type = REG_BINARY;
                break;
            }
        }

        if (type == REG_BINARY) {
            QString s = variantToString(value);
            regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
        } else {
            QStringList::const_iterator it = l.constBegin();
            for (; it != l.constEnd(); ++it) {
                const QString &s = *it;
                regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
            }
            regValueBuff.append((char)0);
            regValueBuff.append((char)0);
        }
        break;
    }

    case QVariant::Int:
    case QVariant::UInt: {
        type = REG_DWORD;
        qint32 i = value.toInt();
        regValueBuff = QByteArray((const char*)&i, sizeof(qint32));
        break;
    }

    case QVariant::LongLong:
    case QVariant::ULongLong: {
        type = REG_QWORD;
        qint64 i = value.toLongLong();
        regValueBuff = QByteArray((const char*)&i, sizeof(qint64));
        break;
    }

    case QVariant::ByteArray:
    // fallthrough intended

    default: {
        // If the string does not contain '\0', we can use REG_SZ, the native registry
        // string type. Otherwise we use REG_BINARY.
        QString s = variantToString(value);
        type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
        if (type == REG_BINARY) {
            regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
        } else {
            regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
        }
        break;
    }
    }

    // set the value
    LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type,
                             reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
                             regValueBuff.size());

    if (res == ERROR_SUCCESS) {
        deleteWriteHandleOnExit = false;
    } else {
        qWarning("QSettings: failed to set subkey \"%s\": %s",
                 rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
        setStatus(QSettings::AccessError);
    }

    RegCloseKey(handle);
}
void ExpandingWidgetModel::rowSelected(const QModelIndex& idx_)
{
  QModelIndex idx( firstColumn(idx_) );
  if( !m_partiallyExpanded.contains( idx ) )
  {
      QModelIndex oldIndex = partiallyExpandedRow();
      //Unexpand the previous partially expanded row
      if( !m_partiallyExpanded.isEmpty() )
      { ///@todo allow multiple partially expanded rows
        while( !m_partiallyExpanded.isEmpty() )
            m_partiallyExpanded.erase(m_partiallyExpanded.begin());
            //partiallyUnExpand( m_partiallyExpanded.begin().key() );
      }
      //Notify the underlying models that the item was selected, and eventually get back the text for the expanding widget.
      if( !idx.isValid() ) {
        //All items have been unselected
        if( oldIndex.isValid() )
          emit dataChanged(oldIndex, oldIndex);
      } else {
        QVariant variant = data(idx, CodeCompletionModel::ItemSelected);

        if( !isExpanded(idx) && variant.type() == QVariant::String) {

          //Either expand upwards or downwards, choose in a way that
          //the visible fields of the new selected entry are not moved.
          if( oldIndex.isValid() && (oldIndex < idx || (!(oldIndex < idx) && oldIndex.parent() < idx.parent()) ) )
            m_partiallyExpanded.insert(idx, ExpandUpwards);
          else
            m_partiallyExpanded.insert(idx, ExpandDownwards);

          //Say that one row above until one row below has changed, so no items will need to be moved(the space that is taken from one item is given to the other)
          if( oldIndex.isValid() && oldIndex < idx ) {
            emit dataChanged(oldIndex, idx);

            if( treeView()->verticalScrollMode() == QAbstractItemView::ScrollPerItem )
            {
              //Qt fails to correctly scroll in ScrollPerItem mode, so the selected index is completely visible,
              //so we do the scrolling by hand.
              QRect selectedRect = treeView()->visualRect(idx);
              QRect frameRect = treeView()->frameRect();

              if( selectedRect.bottom() > frameRect.bottom() ) {
                int diff = selectedRect.bottom() - frameRect.bottom();
                //We need to scroll down
                QModelIndex newTopIndex = idx;

                QModelIndex nextTopIndex = idx;
                QRect nextRect = treeView()->visualRect(nextTopIndex);
                while( nextTopIndex.isValid() && nextRect.isValid() && nextRect.top() >= diff ) {
                  newTopIndex = nextTopIndex;
                  nextTopIndex = treeView()->indexAbove(nextTopIndex);
                  if( nextTopIndex.isValid() )
                    nextRect = treeView()->visualRect(nextTopIndex);
                }
                treeView()->scrollTo( newTopIndex, QAbstractItemView::PositionAtTop );
              }
            }

            //This is needed to keep the item we are expanding completely visible. Qt does not scroll the view to keep the item visible.
            //But we must make sure that it isn't too expensive.
            //We need to make sure that scrolling is efficient, and the whole content is not repainted.
            //Since we are scrolling anyway, we can keep the next line visible, which might be a cool feature.

            //Since this also doesn't work smoothly, leave it for now
            //treeView()->scrollTo( nextLine, QAbstractItemView::EnsureVisible );
          } else if( oldIndex.isValid() &&  idx < oldIndex ) {
            emit dataChanged(idx, oldIndex);

            //For consistency with the down-scrolling, we keep one additional line visible above the current visible.

            //Since this also doesn't work smoothly, leave it for now
/*            QModelIndex prevLine = idx.sibling(idx.row()-1, idx.column());
            if( prevLine.isValid() )
                treeView()->scrollTo( prevLine );*/
          } else
            emit dataChanged(idx, idx);
        } else if( oldIndex.isValid() ) {
          //We are not partially expanding a new row, but we previously had a partially expanded row. So signalize that it has been unexpanded.

            emit dataChanged(oldIndex, oldIndex);
        }
    }
  }else{
    qCDebug( PLUGIN_QUICKOPEN ) << "ExpandingWidgetModel::rowSelected: Row is already partially expanded";
  }
}
void ChangeProperties::on_buttonSet_clicked()
{
    QTreeWidgetItem *item = listProperties->currentItem();
    if (!item)
	return;
    
    QString prop = item->text(0);
    QVariant value = activex->property(prop.toLatin1());
    QVariant::Type type = value.type();
    if (!value.isValid()) {
	const QMetaObject *mo = activex->metaObject();
	const QMetaProperty property = mo->property(mo->indexOfProperty(prop.toLatin1()));
	type = QVariant::nameToType(property.typeName());
    }
    switch (type) {
    case QVariant::Color:
	{
	    QColor col;
	    col.setNamedColor(editValue->text());
	    if (col.isValid()) {
		value = qVariantFromValue(col);
	    } else {
		QMessageBox::warning(this, tr("Can't parse input"), 
		                           tr("Failed to create a color from %1\n"
					                "The string has to be a valid color name (e.g. 'red')\n"
							"or a RGB triple of format '#rrggbb'."
							).arg(editValue->text()));
	    }
	}
	break;
    case QVariant::Font:
	{
	    QFont fnt;
	    if (fnt.fromString(editValue->text())) {
		value = qVariantFromValue(fnt);
	    } else {
		QMessageBox::warning(this, tr("Can't parse input"), 
		                           tr("Failed to create a font from %1\n"
					        "The string has to have a format family,<point size> or\n"
						"family,pointsize,stylehint,weight,italic,underline,strikeout,fixedpitch,rawmode."
							).arg(editValue->text()));
	    }
	}
	break;
    case QVariant::Pixmap:
	{
	    QString fileName = editValue->text();
	    if (fileName.isEmpty())
		fileName = QFileDialog::getOpenFileName(this);
	    QPixmap pm(fileName);
	    if (pm.isNull())
		return;

	    value = qVariantFromValue(pm);
	}
	break;
    case QVariant::Bool:
	{
	    QString txt = editValue->text().toLower();
	    value = QVariant(txt != QLatin1String("0") && txt != QLatin1String("false"));
	}
	break;
    case QVariant::List:
	{
	    QStringList txtList = editValue->text().split(QRegExp(QLatin1String("[,;]")));
	    QList<QVariant> varList;
	    for (int i = 0; i < txtList.count(); ++i) {
		QVariant svar(txtList.at(i));
		QString str = svar.toString();
		str = str.trimmed();
		bool ok;
		int n = str.toInt(&ok);
		if (ok) {
		    varList << n;
		    continue;
		}
		double d = str.toDouble(&ok);
		if (ok) {
		    varList << d;
		    continue;
		}
		varList << str;
	    }
	    value = varList;
	}
	break;

    default:
	value = editValue->text();
	break;
    }
 
    Q_ASSERT(activex->setProperty(prop.toLatin1(), value));
    updateProperties();
    listProperties->setCurrentItem(listProperties->findItems(prop, Qt::MatchExactly).at(0));
}
Example #8
0
QWidget*  MultiDelegate::createEditor( QWidget* parent,
                                     const QStyleOptionViewItem& option,
                                     const QModelIndex& index)  const
{
    const QAbstractItemModel*  model = index.model();
    QVariant  value = model->data( index, Qt::EditRole);
    switch (value.type()) {
    case QMetaType::QTime:
    {
        QTimeEdit*  editor = new QTimeEdit( parent);
        editor->setMaximumWidth( editor->sizeHint().width());

        //// Get value snapshot into editor
        editor->setTime( value.toTime());
        return editor;
    }
    case QMetaType::QDate:
    {
        QDateEdit*  editor = new QDateEdit( parent);
        setupCalenderWidget( editor);
        editor->setMaximumWidth( editor->sizeHint().width());

        //// Get value snapshot into editor
        editor->setDate( value.toDate());
        return editor;
    }
    case QMetaType::QDateTime:
    {
        QDateTimeEdit*  editor = new QDateTimeEdit( parent);
        setupCalenderWidget( editor);
        editor->setMaximumWidth( editor->sizeHint().width());

        editor->setDateTime( value.toDateTime());
        return editor;
    }
    case QMetaType::QImage:
        // Fall throu
    case QMetaType::QPixmap:
        // Fall throu
    case QMetaType::QIcon:
    {
        PixmapViewer*  editor = new PixmapViewer( parent);
        connect( editor, SIGNAL(finished(int)), this, SLOT(closeEmittingEditor()));
        return editor;
    }
    case QMetaType::QStringList:
    {
        QVariant  varList = index.model()->data( index, ItemDataRole::EnumList);
        if (varList.isNull())  break;  // Not a enum-list, fall to std

        QListWidget*  editor = new QListWidget( parent);
        foreach (const QString& bitItemText, varList.toStringList()) {
            QListWidgetItem* bitItem = new QListWidgetItem( bitItemText, editor);
            bitItem->setFlags(bitItem->flags() | Qt::ItemIsUserCheckable);
            bitItem->setCheckState(Qt::Unchecked);
        }
        int width  = editor->sizeHintForColumn(0) + 25;
        int height = editor->sizeHintForRow(0) * editor->count() + 10;
        editor->setMinimumWidth( width);
        editor->setMaximumWidth( width);
        editor->setMinimumHeight( height);
        editor->setMaximumHeight( height);

        //// Get value snapshot into editor
        QStringList  valList = value.toStringList();
        int  itemCount = editor->count();
        for (int i = 0; i < itemCount; ++i) {
            QListWidgetItem*  bitItem = editor->item(i);
            bool  isActive = valList.contains( bitItem->text());
            bitItem->setCheckState( isActive ? Qt::Checked : Qt::Unchecked);
        }
        return editor;
    }
    case QMetaType::QString:
    {
        QVariant  varList = index.model()->data( index, ItemDataRole::EnumList);
        if (varList.isNull())  break;  // Not a enum-list, fall to std

        QComboBox*  editor = new QComboBox( parent);
        editor->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        editor->addItems( varList.toStringList());
        editor->setMaximumWidth( editor->minimumSizeHint().width());

        //// Get value snapshot into editor
        editor->setCurrentIndex( editor->findText( value.toString()));
        return editor;
    }
    default:;
    }

    if (index.column() == 0) {
        emit itemEditTrigged( index);
        return 0;  // No inline editor
    }

    QWidget*  editor = QItemDelegate::createEditor( parent, option, index);

    //// Get value snapshot into editor
    QItemDelegate::setEditorData( editor, index);
    return editor;
}
/*
    Converts \a var to \a arg, and tries to coerce \a arg to \a type.

    Used by

    QAxServerBase:
        - QAxServerBase::qt_metacall
        - IDispatch::Invoke(PROPERTYGET, METHOD)
        - IPersistPropertyBag::Save

    QAxBase:
        - IDispatch::Invoke (QAxEventSink)
        - QAxBase::internalProperty(WriteProperty)
        - QAxBase::internalInvoke()
        - QAxBase::dynamicCallHelper()
        - IPropertyBag::Read (QtPropertyBag)

    Also called recoursively for lists.
*/
bool QVariantToVARIANT(const QVariant &var, VARIANT &arg, const QByteArray &typeName, bool out)
{
    QVariant qvar = var;
    // "type" is the expected type, so coerce if necessary
    QVariant::Type proptype = typeName.isEmpty() ? QVariant::Invalid : QVariant::nameToType(typeName);
    if (proptype == QVariant::UserType && !typeName.isEmpty()) {
        if (typeName == "short" || typeName == "char")
            proptype = QVariant::Int;
        else if (typeName == "float")
            proptype = QVariant::Double;
    }
    if (proptype != QVariant::Invalid && proptype != QVariant::UserType && proptype != qvar.type()) {
        if (qvar.canConvert(proptype))
            qvar.convert(proptype);
        else
            qvar = QVariant(proptype);
    }

    if (out && arg.vt == (VT_VARIANT|VT_BYREF) && arg.pvarVal) {
        return QVariantToVARIANT(var, *arg.pvarVal, typeName, false);
    }

    if (out && proptype == QVariant::Invalid && typeName == "QVariant") {
        VARIANT *pVariant = new VARIANT;
        QVariantToVARIANT(var, *pVariant, QByteArray(), false);
        arg.vt = VT_VARIANT|VT_BYREF;
        arg.pvarVal = pVariant;
        return true;
    }

    switch ((int)qvar.type()) {
    case QVariant::String:
        if (out && arg.vt == (VT_BSTR|VT_BYREF)) {
            if (*arg.pbstrVal)
                SysFreeString(*arg.pbstrVal);
            *arg.pbstrVal = QStringToBSTR(qvar.toString());
            arg.vt = VT_BSTR|VT_BYREF;
        } else {
            arg.vt = VT_BSTR;
            arg.bstrVal = QStringToBSTR(qvar.toString());
            if (out) {
                arg.pbstrVal = new BSTR(arg.bstrVal);
                arg.vt |= VT_BYREF;
            }
        }
        break;
        
    case QVariant::Int:
        if (out && arg.vt == (VT_I4|VT_BYREF)) {
            *arg.plVal = qvar.toInt();
        } else {
            arg.vt = VT_I4;
            arg.lVal = qvar.toInt();
            if (out) {
                if (typeName == "short") {
                    arg.vt = VT_I2;
                    arg.piVal = new short(arg.lVal);
                } else if (typeName == "char") {
                    arg.vt = VT_I1;
                    arg.pcVal= new char(arg.lVal);
                } else {
                    arg.plVal = new long(arg.lVal);
                }
                arg.vt |= VT_BYREF;
            }
        }
        break;
        
    case QVariant::UInt:
        if (out && (arg.vt == (VT_UINT|VT_BYREF) || arg.vt == (VT_I4|VT_BYREF))) {
            *arg.puintVal = qvar.toUInt();
        } else {
            arg.vt = VT_UINT;
            arg.uintVal = qvar.toUInt();
            if (out) {
                arg.puintVal = new uint(arg.uintVal);
                arg.vt |= VT_BYREF;
            }
        }
        break;
        
    case QVariant::LongLong:
        if (out && arg.vt == (VT_CY|VT_BYREF)) {
            arg.pcyVal->int64 = qvar.toLongLong();
#if !defined(Q_OS_WINCE) && defined(_MSC_VER) && _MSC_VER >= 1400
        } else if (out && arg.vt == (VT_I8|VT_BYREF)) {
            *arg.pllVal = qvar.toLongLong();
        } else {
            arg.vt = VT_I8;
            arg.llVal = qvar.toLongLong();
            if (out) {
                arg.pllVal = new LONGLONG(arg.llVal);
                arg.vt |= VT_BYREF;
            }
        }
#else
        } else {
Example #10
0
/*!
    Renders the delegate using the given \a painter and style \a option for
    the item specified by \a index.

    When reimplementing this function in a subclass, you should update the area
    held by the option's \l{QStyleOption::rect}{rect} variable, using the
    option's \l{QStyleOption::state}{state} variable to determine the state of
    the item to be displayed, and adjust the way it is painted accordingly.

    For example, a selected item may need to be displayed differently to
    unselected items, as shown in the following code:

    \snippet itemviews/pixelator/pixeldelegate.cpp 2
    \dots

    After painting, you should ensure that the painter is returned to its
    the state it was supplied in when this function was called. For example,
    it may be useful to call QPainter::save() before painting and
    QPainter::restore() afterwards.

    \sa QStyle::State
*/
void QItemDelegate::paint(QPainter *painter,
                          const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
{
    Q_D(const QItemDelegate);
    Q_ASSERT(index.isValid());

    QStyleOptionViewItem opt = setOptions(index, option);

    // prepare
    painter->save();
    if (d->clipPainting)
        painter->setClipRect(opt.rect);

    // get the data and the rectangles

    QVariant value;

    QPixmap pixmap;
    QRect decorationRect;
    value = index.data(Qt::DecorationRole);
    if (value.isValid()) {
        // ### we need the pixmap to call the virtual function
        pixmap = decoration(opt, value);
        if (value.type() == QVariant::Icon) {
            d->tmp.icon = qvariant_cast<QIcon>(value);
            d->tmp.mode = d->iconMode(option.state);
            d->tmp.state = d->iconState(option.state);
            const QSize size = d->tmp.icon.actualSize(option.decorationSize,
                                                      d->tmp.mode, d->tmp.state);
            decorationRect = QRect(QPoint(0, 0), size);
        } else {
            d->tmp.icon = QIcon();
            decorationRect = QRect(QPoint(0, 0), pixmap.size());
        }
    } else {
        d->tmp.icon = QIcon();
        decorationRect = QRect();
    }

    QString text;
    QRect displayRect;
    value = index.data(Qt::DisplayRole);
    if (value.isValid() && !value.isNull()) {
        text = QItemDelegatePrivate::valueToText(value, opt);
        displayRect = textRectangle(painter, d->textLayoutBounds(opt), opt.font, text);
    }

    QRect checkRect;
    Qt::CheckState checkState = Qt::Unchecked;
    value = index.data(Qt::CheckStateRole);
    if (value.isValid()) {
        checkState = static_cast<Qt::CheckState>(value.toInt());
        checkRect = doCheck(opt, opt.rect, value);
    }

    // do the layout

    doLayout(opt, &checkRect, &decorationRect, &displayRect, false);

    // draw the item

    drawBackground(painter, opt, index);
    drawCheck(painter, opt, checkRect, checkState);
    drawDecoration(painter, opt, decorationRect, pixmap);
    drawDisplay(painter, opt, displayRect, text);
    drawFocus(painter, opt, displayRect);

    // done
    painter->restore();
}
QString QGalleryTrackerStringListColumn::toString(const QVariant &variant) const
{
    return variant.type() == QVariant::StringList
        ? variant.toStringList().join(m_separatorString)
        : variant.toString();
}
Example #12
0
void TestObject::setVariant(const QVariant &value)
{
    qDebug() << value.type();
}
Example #13
0
static void streamDebug(QDebug dbg, const QVariant &v)
{
    switch(v.type()) {
    case QVariant::Cursor:
#ifndef QT_NO_CURSOR
//        dbg.nospace() << qvariant_cast<QCursor>(v); //FIXME
#endif
        break;
    case QVariant::Bitmap:
//        dbg.nospace() << qvariant_cast<QBitmap>(v); //FIXME
        break;
    case QVariant::Polygon:
        dbg.nospace() << qvariant_cast<QPolygon>(v);
        break;
    case QVariant::Region:
        dbg.nospace() << qvariant_cast<QRegion>(v);
        break;
    case QVariant::Font:
//        dbg.nospace() << qvariant_cast<QFont>(v);  //FIXME
        break;
    case QVariant::Matrix:
        dbg.nospace() << qvariant_cast<QMatrix>(v);
        break;
    case QVariant::Transform:
        dbg.nospace() << qvariant_cast<QTransform>(v);
        break;
    case QVariant::Pixmap:
//        dbg.nospace() << qvariant_cast<QPixmap>(v); //FIXME
        break;
    case QVariant::Image:
//        dbg.nospace() << qvariant_cast<QImage>(v); //FIXME
        break;
    case QVariant::Brush:
        dbg.nospace() << qvariant_cast<QBrush>(v);
        break;
    case QVariant::Color:
        dbg.nospace() << qvariant_cast<QColor>(v);
        break;
    case QVariant::Palette:
//        dbg.nospace() << qvariant_cast<QPalette>(v); //FIXME
        break;
#ifndef QT_NO_ICON
    case QVariant::Icon:
//        dbg.nospace() << qvariant_cast<QIcon>(v); // FIXME
        break;
#endif
    case QVariant::SizePolicy:
//        dbg.nospace() << qvariant_cast<QSizePolicy>(v); //FIXME
        break;
#ifndef QT_NO_SHORTCUT
    case QVariant::KeySequence:
        dbg.nospace() << qvariant_cast<QKeySequence>(v);
        break;
#endif
    case QVariant::Pen:
        dbg.nospace() << qvariant_cast<QPen>(v);
        break;
#ifndef QT_NO_MATRIX4X4
    case QVariant::Matrix4x4:
        dbg.nospace() << qvariant_cast<QMatrix4x4>(v);
        break;
#endif
#ifndef QT_NO_VECTOR2D
    case QVariant::Vector2D:
        dbg.nospace() << qvariant_cast<QVector2D>(v);
        break;
#endif
#ifndef QT_NO_VECTOR3D
    case QVariant::Vector3D:
        dbg.nospace() << qvariant_cast<QVector3D>(v);
        break;
#endif
#ifndef QT_NO_VECTOR4D
    case QVariant::Vector4D:
        dbg.nospace() << qvariant_cast<QVector4D>(v);
        break;
#endif
#ifndef QT_NO_QUATERNION
    case QVariant::Quaternion:
        dbg.nospace() << qvariant_cast<QQuaternion>(v);
        break;
#endif
    default:
        qcoreVariantHandler()->debugStream(dbg, v);
        break;
    }
}
Example #14
0
SEXP to_sexp(QVariant variant) {
  SEXP ans = NULL;
  switch(variant.type()) {
  case QMetaType::Void:
    ans = R_NilValue;
    break;
  case QMetaType::UChar:
    ans = ScalarRaw(variant.value<unsigned char>());
    break;
  case QMetaType::Bool:
    ans = ScalarLogical(variant.value<bool>());
    break;
  case QMetaType::Int:
  case QMetaType::UInt:
  case QMetaType::Long:
  case QMetaType::Short:
  case QMetaType::UShort:
    ans = ScalarInteger(variant.value<int>());
    break;
  case QMetaType::Double:
  case QMetaType::LongLong:
  case QMetaType::ULong:
  case QMetaType::ULongLong:
  case QMetaType::Float:
    ans = ScalarReal(variant.value<double>());
    break;
  case QMetaType::QChar:
  case QMetaType::Char:
  case QMetaType::QString:
    ans = qstring2sexp(variant.value<QString>());
    break;
  case QMetaType::QByteArray:
    ans = to_sexp(variant.value<QByteArray>());
    break;
  case QMetaType::VoidStar:
    ans = wrapPointer(variant.value<void *>());
    break;
  case QMetaType::QObjectStar:
    ans = ptr_to_sexp(variant.value<QObject *>(),
                      SmokeType(qt_Smoke, "QObject"));
    break;
  case QMetaType::QWidgetStar:
    ans = ptr_to_sexp(variant.value<QWidget *>(),
                      SmokeType(qt_Smoke, "QWidget"));
    break;
  case QMetaType::QCursor:
    ans = QVARIANT_TO_SEXP(variant, QCursor);
    break;
  case QMetaType::QDate:
    ans = QVARIANT_TO_SEXP(variant, QDate);
    break;
  case QMetaType::QSize:
    ans = QVARIANT_TO_SEXP(variant, QSize);
  case QMetaType::QSizeF:
    ans = QVARIANT_TO_SEXP(variant, QSizeF);
    break;
  case QMetaType::QTime:
    ans = QVARIANT_TO_SEXP(variant, QTime);
    break;
  case QMetaType::QVariantList:
    ans = to_sexp(variant.value<QVariantList>(),
                  SmokeType(qt_Smoke, "QList<QVariant>"));
    break;
  case QMetaType::QPolygon:
    ans = QVARIANT_TO_SEXP(variant, QPolygon);
    break;
  case QMetaType::QColor:
    ans = QVARIANT_TO_SEXP(variant, QColor);
    break;
  case QMetaType::QRectF:
    ans = QVARIANT_TO_SEXP(variant, QRectF);
    break;
  case QMetaType::QRect:
    ans = QVARIANT_TO_SEXP(variant, QRect);
    break;
  case QMetaType::QLine:
    ans = QVARIANT_TO_SEXP(variant, QLine);
    break;
  case QMetaType::QTextLength:
    ans = QVARIANT_TO_SEXP(variant, QTextLength);
    break;
  case QMetaType::QStringList:
    ans = to_sexp(variant.value<QStringList>(),
                  SmokeType(qt_Smoke, "QStringList"));
    break;
  case QMetaType::QVariantMap:
    ans = to_sexp(variant.value<QVariantMap>(),
                  SmokeType(qt_Smoke, "QMap<QString,QVariant>"));
    break;
  case QMetaType::QVariantHash:
    ans = to_sexp(variant.value<QVariantHash>(),
                  SmokeType(qt_Smoke, "QHash<QString,QVariant>"));
    break;
  case QMetaType::QIcon:
    ans = QVARIANT_TO_SEXP(variant, QIcon);
    break;
  case QMetaType::QPen:
    ans = QVARIANT_TO_SEXP(variant, QPen);
    break;
  case QMetaType::QLineF:
    ans = QVARIANT_TO_SEXP(variant, QLineF);
    break;
  case QMetaType::QTextFormat:
    ans = QVARIANT_TO_SEXP(variant, QTextFormat);
    break;
  case QMetaType::QPoint:
    ans = QVARIANT_TO_SEXP(variant, QPoint);
    break;
  case QMetaType::QPointF:
    ans = QVARIANT_TO_SEXP(variant, QPointF);
    break;
  case QMetaType::QUrl:
    ans = QVARIANT_TO_SEXP(variant, QUrl);
    break;
  case QMetaType::QRegExp:
    ans = QVARIANT_TO_SEXP(variant, QRegExp);
    break;
  case QMetaType::QDateTime:
    ans = QVARIANT_TO_SEXP(variant, QDateTime);
    break;
  case QMetaType::QPalette:
    ans = QVARIANT_TO_SEXP(variant, QPalette);
    break;
  case QMetaType::QFont:
    ans = QVARIANT_TO_SEXP(variant, QFont);
    break;
  case QMetaType::QBrush:
    ans = QVARIANT_TO_SEXP(variant, QBrush);
    break;
  case QMetaType::QRegion:
    ans = QVARIANT_TO_SEXP(variant, QRegion);
    break;
  case QMetaType::QBitArray:
    ans = QVARIANT_TO_SEXP(variant, QBitArray);
    break;
  case QMetaType::QImage:
    ans = QVARIANT_TO_SEXP(variant, QImage);
    break;
  case QMetaType::QKeySequence:
    ans = QVARIANT_TO_SEXP(variant, QKeySequence);
    break;
  case QMetaType::QSizePolicy:
    ans = QVARIANT_TO_SEXP(variant, QSizePolicy);
    break;
  case QMetaType::QPixmap:
    ans = QVARIANT_TO_SEXP(variant, QPixmap);
    break;
  case QMetaType::QLocale:
    ans = QVARIANT_TO_SEXP(variant, QLocale);
    break;
  case QMetaType::QBitmap:
    ans = QVARIANT_TO_SEXP(variant, QBitmap);
    break;
  case QMetaType::QMatrix: /* obsolete */
    ans = QVARIANT_TO_SEXP(variant, QMatrix);
    break;
#if QT_VERSION >= 0x40300
  case QMetaType::QTransform:
    ans = QVARIANT_TO_SEXP(variant, QTransform);
    break;
#endif
#if QT_VERSION >= 0x40600
  case QMetaType::QMatrix4x4:
    ans = QVARIANT_TO_SEXP(variant, QMatrix4x4);
    break;
  case QMetaType::QVector2D:
    ans = QVARIANT_TO_SEXP(variant, QVector2D);
    break;
  case QMetaType::QVector3D:
    ans = QVARIANT_TO_SEXP(variant, QVector3D);
    break;
  case QMetaType::QVector4D:
    ans = QVARIANT_TO_SEXP(variant, QVector4D);
    break;
  case QMetaType::QQuaternion:
    ans = QVARIANT_TO_SEXP(variant, QQuaternion);
    break;
#endif
  case QMetaType::User:
    break;
  default:
    error("Converting from QVariant: unhandled Qt type");
  }
  if (!ans)
    error("Converting from QVariant: Qt type not yet implemented");
  return ans;
}
Example #15
0
PyObject* scribus_getproperty(PyObject* /*self*/, PyObject* args, PyObject* kw)
{
	PyObject* objArg = NULL;
	char* propertyName = NULL;
	char* kwargs[] = {const_cast<char*>("object"),
					  const_cast<char*>("property"),
					  NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kw, "Oes", kwargs,
				&objArg, "ascii", &propertyName))
		return NULL;

	// Get the QObject* the object argument refers to
	QObject* obj = getQObjectFromPyArg(objArg);
	if (!obj)
		return NULL;
	objArg = NULL; // no need to decref, it's borrowed

	// Get the QMetaProperty for the property, so we can check
	// if it's a set/enum and do name/value translation.
	const QMetaObject* objmeta = obj->metaObject();
	int i = objmeta->indexOfProperty(propertyName);
	if (i == -1)
	{
		PyErr_SetString(PyExc_ValueError,
				QObject::tr("Property not found").toLocal8Bit().data());
		return NULL;
	}

	QMetaProperty propmeta = objmeta->property(i);
	if (!propmeta.isValid())
	{
		PyErr_SetString(PyExc_ValueError,
				QObject::tr("Invalid property").toLocal8Bit().data());
		return NULL;
	}

	// Get the property value as a variant type
	QVariant prop = obj->property(propertyName);

	// Convert the property to an instance of the closest matching Python type.
	PyObject* resultobj = NULL;
	// NUMERIC TYPES
	if (prop.type() == QVariant::Int)
		resultobj = PyLong_FromLong(prop.toInt());
	else if (prop.type() == QVariant::Double)
		resultobj = PyFloat_FromDouble(prop.toDouble());
	// BOOLEAN
	else if (prop.type() == QVariant::Bool)
		resultobj = PyBool_FromLong(prop.toBool());
	// STRING TYPES
	else if (prop.type() == QVariant::ByteArray)
		resultobj = PyString_FromString(prop.toByteArray().data());
	else if (prop.type() == QVariant::String)
		resultobj = PyString_FromString(prop.toString().toUtf8().data());
	// HIGHER ORDER TYPES
	else if (prop.type() == QVariant::Point)
	{
		// Return a QPoint as an (x,y) tuple.
		QPoint pt = prop.toPoint();
		return Py_BuildValue("(ii)", pt.x(), pt.y());
	}
	else if (prop.type() == QVariant::Rect)
	{
		// Return a QRect as an (x,y,width,height) tuple.
		// FIXME: We should really construct and return an object that
		// matches the API of QRect and has properties to keep
		// left/top/right/bottom and x/y/width/height in sync.
		QRect r = prop.toRect();
		return Py_BuildValue("(iiii)", r.x(), r.y(), r.width(), r.height());
	}
	else if (prop.type() == QVariant::StringList)
	{
		QStringList tmp = prop.toStringList();
		return convert_QStringList_to_PyListObject(tmp);
	}
	// UNHANDLED TYPE
	else
	{
		PyErr_SetString(PyExc_TypeError, QObject::tr("Couldn't convert result type '%1'.").arg(prop.typeName()).toLocal8Bit().constData() );
		return resultobj;
	}

	// Return the resulting Python object
	if (resultobj == NULL)
	{
		// An exception was set while assigning to resultobj
		assert(PyErr_Occurred());
		return NULL;
	}
	else
		return resultobj;
}
Example #16
0
void EffectWidgetPrivate::autogenerateUi()
{
    Q_Q(EffectWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(q);
    mainLayout->setMargin(0);
    foreach (const EffectParameter &para, effect->parameters()) {
        QVariant value = effect->parameterValue(para);
        QHBoxLayout *pLayout = new QHBoxLayout;
        mainLayout->addLayout(pLayout);

        QLabel *label = new QLabel(q);
        pLayout->addWidget(label);
        label->setText(para.name());
#ifndef QT_NO_TOOLTIP
        label->setToolTip(para.description());
#endif

        QWidget *control = 0;
        switch (para.type()) {
        case QVariant::String:
            {
                QComboBox *cb = new QComboBox(q);
                control = cb;
                if (value.type() == QVariant::Int) {
                    //value just defines the item index
                    foreach (const QVariant &item, para.possibleValues()) {
                        cb->addItem(item.toString());
                    }
                    cb->setCurrentIndex(value.toInt());
                    QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int)));
                } else {
                    foreach (const QVariant &item, para.possibleValues()) {
                        cb->addItem(item.toString());
                        if (item == value) {
                            cb->setCurrentIndex(cb->count() - 1);
                        }
                    }
                    QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString)));
                }
            }
            break;
        case QVariant::Bool:
            {
                QCheckBox *cb = new QCheckBox(q);
                control = cb;
                cb->setChecked(value.toBool());
                QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool)));
            }
            break;
        case QVariant::Int:
            {
                QSpinBox *sb = new QSpinBox(q);
                control = sb;
                bool minValueOk = false;
                bool maxValueOk = false;
                const int minValue = para.minimumValue().toInt(&minValueOk);
                const int maxValue = para.minimumValue().toInt(&maxValueOk);

                sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT);
                sb->setValue(value.toInt());
                QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int)));
            }
            break;
        case QVariant::Double:
            {
                const double minValue = (para.minimumValue().type() == QVariant::Double ?
                    para.minimumValue().toDouble() : DEFAULT_MIN);
                const double maxValue = (para.maximumValue().type() == QVariant::Double ?
                    para.maximumValue().toDouble() : DEFAULT_MAX);

                if (minValue == -1. && maxValue == 1.) {
                    //Special case values between -1 and 1.0 to use a slider for improved usability
                    QSlider *slider = new QSlider(Qt::Horizontal, q);
                    slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE);
                    slider->setValue(int(SLIDER_RANGE * value.toDouble()));
                    slider->setTickPosition(QSlider::TicksBelow);
                    slider->setTickInterval(TICKINTERVAL);
                    QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int)));
                } else {
                    double step = 0.1;
                    if (qAbs(maxValue - minValue) > 50)
                        step = 1.0;
                    QDoubleSpinBox *sb = new QDoubleSpinBox(q);
                    control = sb;
                    sb->setRange(minValue, maxValue);
                    sb->setValue(value.toDouble());
                    sb->setSingleStep(step);
                    QObject::connect(sb, SIGNAL(valueChanged(double)), q,
                        SLOT(_k_setDoubleParameter(double)));
                }
            }
            break;
        default:
            break;
        }
Example #17
0
    QString ActionInstance::evaluateTextString(bool &ok, const QString &toEvaluate, int &position)
	{
		ok = true;

		int startIndex = position;

		QString result;

		while(position < toEvaluate.length())
		{
			if(toEvaluate[position] == QLatin1Char('$'))
			{
				//find a variable name
				if(VariableRegExp.indexIn(toEvaluate, position) != -1)
				{
					QString foundVariableName = VariableRegExp.cap(1);
					QScriptValue foundVariable = d->scriptEngine->globalObject().property(foundVariableName);

					position += foundVariableName.length();

					if(!foundVariable.isValid())
					{
						ok = false;

						emit executionException(ActionException::InvalidParameterException, tr("Undefined variable \"%1\"").arg(foundVariableName));
						return QString();
					}

					QString stringEvaluationResult;

					if(foundVariable.isNull())
						stringEvaluationResult = QStringLiteral("[Null]");
					else if(foundVariable.isUndefined())
						stringEvaluationResult = QStringLiteral("[Undefined]");
					else if(foundVariable.isArray())
					{
						while((position + 1 < toEvaluate.length()) && toEvaluate[position + 1] == QLatin1Char('['))
						{
							position += 2;
							QString indexArray = evaluateTextString(ok, toEvaluate, position);

							if((position < toEvaluate.length()) && toEvaluate[position] == QLatin1Char(']'))
							{
								QScriptString internalIndexArray = d->scriptEngine->toStringHandle(indexArray);
								bool flag = true;
								int numIndex = internalIndexArray.toArrayIndex(&flag);

								if(flag) //numIndex is valid
									foundVariable = foundVariable.property(numIndex);
								else //use internalIndexArray
									foundVariable = foundVariable.property(internalIndexArray);
							}
							else
							{
								//syntax error
								ok = false;

								emit executionException(ActionException::InvalidParameterException, tr("Invalid parameter. Unable to evaluate string"));
								return QString();
							}

							//COMPATIBILITY: we break the while loop if foundVariable is no more of Array type
							if(!foundVariable.isArray())
								break;
						}
						//end of while, no more '['
						if(foundVariable.isArray())
							stringEvaluationResult = evaluateVariableArray(ok, foundVariable);
						else
							stringEvaluationResult = foundVariable.toString();
					}
					else if(foundVariable.isVariant())
					{
						QVariant variantEvaluationResult = foundVariable.toVariant();
						switch(variantEvaluationResult.type())
						{
						case QVariant::StringList:
							stringEvaluationResult = variantEvaluationResult.toStringList().join(QStringLiteral("\n"));
							break;
						case QVariant::ByteArray:
							stringEvaluationResult = QStringLiteral("[Raw data]");
							break;
						default:
							stringEvaluationResult = foundVariable.toString();
							break;
						}
					}
					else
						stringEvaluationResult = foundVariable.toString();

					result.append(stringEvaluationResult);
				}

			}
			else if (toEvaluate[position] == QLatin1Char(']'))
			{
				if(startIndex == 0)
					//in top level evaluation isolated character ']' is accepted (for compatibility reason), now prefer "\]"
					//i.e without matching '['
					result.append(toEvaluate[position]);
				else
					//on other levels, the parsing is stopped at this point
					return result;
			}
			else if(toEvaluate[position] == QLatin1Char('\\'))
			{
				if(startIndex == 0)
				{
					//for ascendant compatibility reason
					//in top level evaluation '\' is not only an escape character,
					//but can also be a standard character in some cases
					if((position + 1) < toEvaluate.length())
					{
						position++;
						if(toEvaluate[position] == QLatin1Char('$') || toEvaluate[position] == QLatin1Char('[') || toEvaluate[position] == QLatin1Char(']') || toEvaluate[position] == QLatin1Char('\\'))
							result.append(toEvaluate[position]);
						else
						{
							position--;
							result.append(toEvaluate[position]);
						}
					}
					else
						result.append(toEvaluate[position]);
				}
				else
				{
					position++;
					if( position < toEvaluate.length() )
						result.append(toEvaluate[position]);
				}
			}
			else
				result.append(toEvaluate[position]);

			position++;
		}

		return result;
	}
Example #18
0
void KNConfigure::setData(const QString &key, const QVariant &value)
{
    //Check whether the value is null.
    if(value.isNull())
    {
        //Remove the key from the configure data.
        m_dataObject.remove(key);
        //Complete.
        return;
    }
    //Because the QJsonObject can only insert QJsonValue, and the construct
    //function of QJsonValue only have the following types:
    //   bool, QString, array, double, object.
    //So we have to translate some complex type variant to object.
    switch(value.type())
    {
    //For the basic types(double, float, int, bool, QString), we will save them
    //directly.
    case QVariant::LongLong:
        m_dataObject.insert(key, value.toLongLong());
        break;
    case QVariant::Double:
        m_dataObject.insert(key, value.toDouble());
        break;
    case QVariant::String:
        m_dataObject.insert(key, value.toString());
        break;
    case QVariant::Int:
        m_dataObject.insert(key, value.toInt());
        break;
    case QVariant::Bool:
        m_dataObject.insert(key, value.toBool());
        break;
    //For advanced types(like Font), we have to translate them to a object.
    case QVariant::Font:
    {
        //Generate the font object.
        QFont font=value.value<QFont>();
        QJsonObject fontObject;
        fontObject.insert("Type", QString("Font"));
        fontObject.insert("Family", font.family());
        fontObject.insert("Size", font.pixelSize());
        fontObject.insert("Bold", font.bold());
        fontObject.insert("Italic", font.italic());
        fontObject.insert("Underline", font.underline());
        fontObject.insert("Strikeout", font.strikeOut());
        fontObject.insert("Kerning", font.kerning());
        //Insert the font object.
        m_dataObject.insert(key, fontObject);
        break;
    }
    case QVariant::KeySequence:
    {
        //Generate a key sequence object.
        QKeySequence keySequence=value.value<QKeySequence>();
        //A shortcut object.
        QJsonObject shortcutObject;
        shortcutObject.insert("Type", QString("Shortcut"));
        shortcutObject.insert("Key", keySequence.toString(
                                  QKeySequence::PortableText));
        //Insert the key sequence object.
        m_dataObject.insert(key, shortcutObject);
        break;
    }
    //For the JSON object, it is quite wired that QVariant doesn't enumerate the
    //JSON type here, but it will use the meta type json object here.
    case QMetaType::QJsonObject:
    {
        //Check with the value contains the custom type.
        QJsonObject customObject=value.toJsonObject();
        //Check the custom object type is matched.
        if("CustomObject"==customObject.value("Type").toString())
        {
            //Simply insert the json object to the data.
            m_dataObject.insert(key, customObject);
        }
        break;
    }
    //For the JSON array, directly save the original data.
    case QMetaType::QJsonArray:
    {
        //Simply insert the json array to the data.
        m_dataObject.insert(key, value.toJsonArray());
        break;
    }
    default:
        return;
    }
    //Emit the signal.
    emit valueChanged();
}
void ChangeProperties::updateProperties()
{
    bool hasControl = activex && !activex->isNull();
    tabWidget->setEnabled(hasControl);

    listProperties->clear();
    listEditRequests->clear();
    if (hasControl) {
	const QMetaObject *mo = activex->metaObject();
	const int numprops = mo->propertyCount();
	for (int i = mo->propertyOffset(); i < numprops; ++i) {
	    const QMetaProperty property = mo->property(i);
	    QTreeWidgetItem *item = new QTreeWidgetItem(listProperties);
	    item->setText(0, QString::fromLatin1(property.name()));
	    item->setText(1, QString::fromLatin1(property.typeName()));
            if (!property.isDesignable()) {
                item->setTextColor(0, Qt::gray);
                item->setTextColor(1, Qt::gray);
                item->setTextColor(2, Qt::gray);
            }
	    QVariant var = activex->property(property.name());
	    
	    switch (var.type()) {
	    case QVariant::Color:
		{
		    QColor col = qvariant_cast<QColor>(var);
		    item->setText(2, col.name());
		}
		break;
	    case QVariant::Font:
		{
		    QFont fnt = qvariant_cast<QFont>(var);
		    item->setText(2, fnt.toString());
		}
		break;
	    case QVariant::Bool:
		{
		    item->setText(2, var.toBool() ? QLatin1String("true") : QLatin1String("false"));
		}
		break;
	    case QVariant::Pixmap:
		{
		    QPixmap pm = qvariant_cast<QPixmap>(var);
		    item->setIcon(2, pm);
		}
		break;
	    case QVariant::List:
		{
		    QList<QVariant> varList = var.toList();
		    QStringList strList;
		    for (int i = 0; i < varList.count(); ++i) {
			QVariant var = varList.at(i);
			strList << var.toString();
		    }
		    item->setText(2, strList.join(QLatin1String(", ")));
		}
		break;
	    case QVariant::Int:
		if (property.isEnumType()) {
		    const QMetaEnum enumerator = mo->enumerator(mo->indexOfEnumerator(property.typeName()));
		    item->setText(2, QString::fromLatin1(enumerator.valueToKey(var.toInt())));
		    break;
		}
		//FALLTHROUGH
	    default:
		item->setText(2, var.toString());
		break;
	    }

            bool requesting = false;
#if 0
            {
                void *argv[] = { &requesting };
                activex->qt_metacall(QMetaObject::Call(0x10000000) /*RequestingEdit*/, i, argv);
            }
#endif
            if (requesting) {
		QTreeWidgetItem *check = new QTreeWidgetItem(listEditRequests);
                check->setText(0, QString::fromLatin1(property.name()));
                check->setCheckState(0, activex->propertyWritable(property.name()) ? Qt::Checked : Qt::Unchecked);
	    }
	}
        listProperties->setCurrentItem(listProperties->topLevelItem(0));
    } else {
        editValue->clear();
    }
}
Example #20
0
File: mmp.cpp Project: Orpheon/lmms
void multimediaProject::upgrade()
{
	projectVersion version =
		documentElement().attribute( "creatorversion" ).
							replace( "svn", "" );

	if( version < "0.2.1-20070501" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "arpdir" ) )
			{
				int arpdir = el.attribute( "arpdir" ).toInt();
				if( arpdir > 0 )
				{
					el.setAttribute( "arpdir", arpdir - 1 );
				}
				else
				{
					el.setAttribute( "arpdisabled", "1" );
				}
			}
		}

		list = elementsByTagName( "sampletrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.attribute( "vol" ) != "" )
			{
				el.setAttribute( "vol", el.attribute(
						"vol" ).toFloat() * 100.0f );
			}
			else
			{
				QDomNode node = el.namedItem(
							"automation-pattern" );
				if( !node.isElement() ||
					!node.namedItem( "vol" ).isElement() )
				{
					el.setAttribute( "vol", 100.0f );
				}
			}
		}

		list = elementsByTagName( "ladspacontrols" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QDomNode anode = el.namedItem( "automation-pattern" );
			QDomNode node = anode.firstChild();
			while( !node.isNull() )
			{
				if( node.isElement() )
				{
					QString name = node.nodeName();
					if( name.endsWith( "link" ) )
					{
						el.setAttribute( name,
							node.namedItem( "time" )
							.toElement()
							.attribute( "value" ) );
						QDomNode oldNode = node;
						node = node.nextSibling();
						anode.removeChild( oldNode );
						continue;
					}
				}
				node = node.nextSibling();
			}
		}

		QDomNode node = m_head.firstChild();
		while( !node.isNull() )
		{
			if( node.isElement() )
			{
				if( node.nodeName() == "bpm" )
				{
					int value = node.toElement().attribute(
							"value" ).toInt();
					if( value > 0 )
					{
						m_head.setAttribute( "bpm",
									value );
						QDomNode oldNode = node;
						node = node.nextSibling();
						m_head.removeChild( oldNode );
						continue;
					}
				}
				else if( node.nodeName() == "mastervol" )
				{
					int value = node.toElement().attribute(
							"value" ).toInt();
					if( value > 0 )
					{
						m_head.setAttribute(
							"mastervol", value );
						QDomNode oldNode = node;
						node = node.nextSibling();
						m_head.removeChild( oldNode );
						continue;
					}
				}
				else if( node.nodeName() == "masterpitch" )
				{
					m_head.setAttribute( "masterpitch",
						-node.toElement().attribute(
							"value" ).toInt() );
					QDomNode oldNode = node;
					node = node.nextSibling();
					m_head.removeChild( oldNode );
					continue;
				}
			}
			node = node.nextSibling();
		}
	}

	if( version < "0.2.1-20070508" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "chorddisabled" ) )
			{
				el.setAttribute( "chord-enabled",
					!el.attribute( "chorddisabled" )
								.toInt() );
				el.setAttribute( "arp-enabled",
					!el.attribute( "arpdisabled" )
								.toInt() );
			}
			else if( !el.hasAttribute( "chord-enabled" ) )
			{
				el.setAttribute( "chord-enabled", true );
				el.setAttribute( "arp-enabled",
					el.attribute( "arpdir" ).toInt() != 0 );
			}
		}

		while( !( list = elementsByTagName( "channeltrack" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "instrumenttrack" );
		}

		list = elementsByTagName( "instrumenttrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "vol" ) )
			{
				float value = el.attribute( "vol" ).toFloat();
				value = roundf( value * 0.585786438f );
				el.setAttribute( "vol", value );
			}
			else
			{
				QDomNodeList vol_list = el.namedItem(
							"automation-pattern" )
						.namedItem( "vol" ).toElement()
						.elementsByTagName( "time" );
				for( int j = 0; !vol_list.item( j ).isNull();
									++j )
				{
					QDomElement timeEl = list.item( j )
								.toElement();
					int value = timeEl.attribute( "value" )
								.toInt();
					value = (int)roundf( value *
								0.585786438f );
					timeEl.setAttribute( "value", value );
				}
			}
		}
	}


	if( version < "0.3.0-rc2" )
	{
		QDomNodeList list = elementsByTagName( "arpandchords" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.attribute( "arpdir" ).toInt() > 0 )
			{
				el.setAttribute( "arpdir",
					el.attribute( "arpdir" ).toInt() - 1 );
			}
		}
	}

	if( version < "0.3.0" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName(
					"pluckedstringsynth" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "vibedstrings" );
			el.setAttribute( "active0", 1 );
		}

		while( !( list = elementsByTagName( "lb303" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "lb302" );
		}

		while( !( list = elementsByTagName( "channelsettings" ) ).
								isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "instrumenttracksettings" );
		}
	}

	if( version < "0.4.0-20080104" )
	{
		QDomNodeList list = elementsByTagName( "fx" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			if( el.hasAttribute( "fxdisabled" ) &&
				el.attribute( "fxdisabled" ).toInt() == 0 )
			{
				el.setAttribute( "enabled", 1 );
			}
		}
	}

	if( version < "0.4.0-20080118" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName( "fx" ) ).isEmpty() )
		{
			QDomElement fxchain = list.item( 0 ).toElement();
			fxchain.setTagName( "fxchain" );
			QDomNode rack = list.item( 0 ).firstChild();
			QDomNodeList effects = rack.childNodes();
			// move items one level up
			while( effects.count() )
			{
				fxchain.appendChild( effects.at( 0 ) );
			}
			fxchain.setAttribute( "numofeffects",
				rack.toElement().attribute( "numofeffects" ) );
			fxchain.removeChild( rack );
		}
	}

	if( version < "0.4.0-20080129" )
	{
		QDomNodeList list;
		while( !( list =
			elementsByTagName( "arpandchords" ) ).isEmpty() )
		{
			QDomElement aac = list.item( 0 ).toElement();
			aac.setTagName( "arpeggiator" );
			QDomNode cloned = aac.cloneNode();
			cloned.toElement().setTagName( "chordcreator" );
			aac.parentNode().appendChild( cloned );
		}
	}

	if( version < "0.4.0-20080409" )
	{
		QStringList s;
		s << "note" << "pattern" << "bbtco" << "sampletco" << "time";
		for( QStringList::iterator it = s.begin(); it < s.end(); ++it )
		{
			QDomNodeList list = elementsByTagName( *it );
			for( int i = 0; !list.item( i ).isNull(); ++i )
			{
				QDomElement el = list.item( i ).toElement();
				el.setAttribute( "pos",
					el.attribute( "pos" ).toInt()*3 );
				el.setAttribute( "len",
					el.attribute( "len" ).toInt()*3 );
			}
		}
		QDomNodeList list = elementsByTagName( "timeline" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			el.setAttribute( "lp0pos",
				el.attribute( "lp0pos" ).toInt()*3 );
			el.setAttribute( "lp1pos",
				el.attribute( "lp1pos" ).toInt()*3 );
		}
		
	}

	if( version < "0.4.0-20080607" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName( "midi" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "midiport" );
		}
	}

	if( version < "0.4.0-20080622" )
	{
		QDomNodeList list;
		while( !( list = elementsByTagName(
					"automation-pattern" ) ).isEmpty() )
		{
			QDomElement el = list.item( 0 ).toElement();
			el.setTagName( "automationpattern" );
		}

		list = elementsByTagName( "bbtrack" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString s = el.attribute( "name" );
			s.replace( QRegExp( "^Beat/Baseline " ),
							"Beat/Bassline " );
			el.setAttribute( "name", s );
		}
	}

	if( version < "0.4.0-beta1" )
	{
		// convert binary effect-key-blobs to XML
		QDomNodeList list;
		list = elementsByTagName( "effect" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString k = el.attribute( "key" );
			if( !k.isEmpty() )
			{
				const QList<QVariant> l =
					base64::decode( k, QVariant::List ).toList();
				if( !l.isEmpty() )
				{
					QString name = l[0].toString();
					QVariant u = l[1];
					EffectKey::AttributeMap m;
					// VST-effect?
					if( u.type() == QVariant::String )
					{
						m["file"] = u.toString();
					}
					// LADSPA-effect?
					else if( u.type() == QVariant::StringList )
					{
						const QStringList sl = u.toStringList();
						m["plugin"] = sl.value( 0 );
						m["file"] = sl.value( 1 );
					}
					EffectKey key( NULL, name, m );
					el.appendChild( key.saveXML( *this ) );
				}
			}
		}
	}
	if( version < "0.4.0-rc2" )
	{
		QDomNodeList list = elementsByTagName( "audiofileprocessor" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			QString s = el.attribute( "src" );
			s.replace( "drumsynth/misc ", "drumsynth/misc_" );
			s.replace( "drumsynth/r&b", "drumsynth/r_n_b" );
			s.replace( "drumsynth/r_b", "drumsynth/r_n_b" );
			el.setAttribute( "src", s );
		}
		list = elementsByTagName( "lb302" );
		for( int i = 0; !list.item( i ).isNull(); ++i )
		{
			QDomElement el = list.item( i ).toElement();
			int s = el.attribute( "shape" ).toInt();
			if( s >= 1 )
			{
				s--;
			}
			el.setAttribute( "shape", QString("%1").arg(s) );
		}

	}

	// Time-signature
	if ( !m_head.hasAttribute( "timesig_numerator" ) )
	{
		m_head.setAttribute( "timesig_numerator", 4 );
		m_head.setAttribute( "timesig_denominator", 4 );
	}

	if( !m_head.hasAttribute( "mastervol" ) )
	{
		m_head.setAttribute( "mastervol", 100 );
	}
//printf("%s\n", toString( 2 ).toUtf8().constData());
}
bool HStateVariableInfoPrivate::checkValue(
    const QVariant& value, QVariant* acceptableValue, QString* errDescr) const
{
    QVariant tmp(value);

    if (m_dataType == HUpnpDataTypes::Undefined)
    {
        if (errDescr)
        {
            *errDescr = QString(
                "Data type of the state variable [%1] is not defined.").arg(
                m_name);
        }
        return false;
    }

    if (value.type() != m_variantDataType)
    {
        if (m_variantDataType == QVariant::Url)
        {
            // for some reason, QVariant does not provide automatic conversion between
            // QUrl and other types (this includes QString, unfortunately) and until it does,
            // this has to be handled as a special case.
            QUrl valueAsUrl(value.toString());
            if (!valueAsUrl.isValid())
            {
                if (errDescr)
                {
                    *errDescr = QString(
                        "Invalid value for a URL type: [%1]").arg(
                            value.toString());
                }
                return false;
            }

            tmp = valueAsUrl;
        }
        else if (!tmp.convert(m_variantDataType))
        {
            if (errDescr)
            {
                *errDescr = "Data type mismatch.";
            }
            return false;
        }
    }

    if (m_dataType == HUpnpDataTypes::string && m_allowedValueList.size())
    {
        if (m_allowedValueList.indexOf(value.toString()) < 0)
        {
            if (errDescr)
            {
                *errDescr = QString(
                    "Value [%1] is not included in the allowed values list.").arg(
                        value.toString());
            }
            return false;
        }
    }
    else if (HUpnpDataTypes::isRational(m_dataType) && !m_allowedValueRange.isNull())
    {
        qreal tmp = value.toDouble();
        if (tmp < m_allowedValueRange.minimum().toDouble() ||
            tmp > m_allowedValueRange.maximum().toDouble())
        {
            if (errDescr)
            {
                *errDescr = QString(
                    "Value [%1] is not within the specified allowed values range.").arg(
                        value.toString());
            }
            return false;
        }
    }
    else if (HUpnpDataTypes::isNumeric(m_dataType) && !m_allowedValueRange.isNull())
    {
        qlonglong tmp = value.toLongLong();
        if (tmp < m_allowedValueRange.minimum().toLongLong() ||
            tmp > m_allowedValueRange.maximum().toLongLong())
        {
            if (errDescr)
            {
                *errDescr = QString(
                    "Value [%1] is not within the specified allowed values range.").arg(
                        value.toString());
            }
            return false;
        }
    }

    *acceptableValue = tmp;
    return true;
}
Example #22
0
void AccessManager::AccessManagerPrivate::setMetaDataForRequest(QNetworkRequest request, KIO::MetaData& metaData)
{
    // Add any meta data specified within request...
    QVariant userMetaData = request.attribute (static_cast<QNetworkRequest::Attribute>(MetaData));
    if (userMetaData.isValid() && userMetaData.type() == QVariant::Map)
        metaData += userMetaData.toMap();

    metaData.insert(QL1S("PropagateHttpHeader"), QL1S("true"));

    if (request.hasRawHeader("User-Agent")) {
        metaData.insert(QL1S("UserAgent"), request.rawHeader("User-Agent"));
        request.setRawHeader("User-Agent", QByteArray());
    }

    if (request.hasRawHeader("Accept")) {
        metaData.insert(QL1S("accept"), request.rawHeader("Accept"));
        request.setRawHeader("Accept", QByteArray());
    }

    if (request.hasRawHeader("Accept-Charset")) {
        metaData.insert(QL1S("Charsets"), request.rawHeader("Accept-Charset"));
        request.setRawHeader("Accept-Charset", QByteArray());
    }

    if (request.hasRawHeader("Accept-Language")) {
        metaData.insert(QL1S("Languages"), request.rawHeader("Accept-Language"));
        request.setRawHeader("Accept-Language", QByteArray());
    }

    if (request.hasRawHeader("Referer")) {
        metaData.insert(QL1S("referrer"), request.rawHeader("Referer"));
        request.setRawHeader("Referer", QByteArray());
    }

    if (request.hasRawHeader("Content-Type")) {
        metaData.insert(QL1S("content-type"), request.rawHeader("Content-Type"));
        request.setRawHeader("Content-Type", QByteArray());
    }

    if (request.attribute(QNetworkRequest::AuthenticationReuseAttribute) == QNetworkRequest::Manual) {
        metaData.insert(QL1S("no-preemptive-auth-reuse"), QL1S("true"));
    }

    request.setRawHeader("Content-Length", QByteArray());
    request.setRawHeader("Connection", QByteArray());
    request.setRawHeader("If-None-Match", QByteArray());
    request.setRawHeader("If-Modified-Since", QByteArray());
    request.setRawHeader("x-kdewebkit-ignore-disposition", QByteArray());

    QStringList customHeaders;
    Q_FOREACH(const QByteArray &key, request.rawHeaderList()) {
        const QByteArray value = request.rawHeader(key);
        if (value.length())
            customHeaders << (key + QL1S(": ") + value);
    }

    if (!customHeaders.isEmpty()) {
        metaData.insert(QL1S("customHTTPHeader"), customHeaders.join("\r\n"));
    }

    // Append per request meta data, if any...
    if (!requestMetaData.isEmpty()) {
        metaData += requestMetaData;
        // Clear per request meta data...
        requestMetaData.clear();
    }

    // Append per session meta data, if any...
    if (!sessionMetaData.isEmpty()) {
        metaData += sessionMetaData;
    }
}
Example #23
0
std::string fromIniCompatible(const QVariant& Var)
{
  if (Var.type() == QVariant::StringList)
    return Var.toStringList().join(", ").toStdString();
  else return Var.toString().toStdString();
}
Example #24
0
void QPpsObjectPrivate::encodeData(pps_encoder_t *encoder, const char *name, const QVariant &data,
                                   bool *ok)
{
    QString errorFunction;
    pps_encoder_error_t error = PPS_ENCODER_OK;
    switch (data.type()) {
    case QVariant::Bool:
        error = pps_encoder_add_bool(encoder, name, data.toBool());
        errorFunction = QStringLiteral("pps_encoder_add_bool");
        break;
    // We want to support encoding uint even though libpps doesn't support it directly.
    // We can't encode uint as an int since that will lose precision (e.g. 2^31+1 can't be
    // encoded that way). However, we can convert uint to double without losing precision.
    // QVariant.toDouble() conveniently takes care of the conversion for us.
    case QVariant::UInt:
    case QVariant::Double:
        error = pps_encoder_add_double(encoder, name, data.toDouble());
        errorFunction = QStringLiteral("pps_encoder_add_double");
        break;
    case QVariant::Int:
        error = pps_encoder_add_int(encoder, name, data.toInt());
        errorFunction = QStringLiteral("pps_encoder_add_int");
        break;
    case QVariant::LongLong:
        error = pps_encoder_add_int64(encoder, name, data.toLongLong());
        errorFunction = QStringLiteral("pps_encoder_add_int64");
        break;
    case QVariant::String:
        error = pps_encoder_add_string(encoder, name, data.toString().toUtf8().constData());
        errorFunction = QStringLiteral("pps_encoder_add_string");
        break;
    case QVariant::List:
        error = pps_encoder_start_array(encoder, name);
        errorFunction = QStringLiteral("pps_encoder_start_array");
        if (error == PPS_ENCODER_OK) {
            encodeArray(encoder, data.toList(), ok);
            error = pps_encoder_end_array(encoder);
            errorFunction = QStringLiteral("pps_encoder_end_array");
        }
        break;
    case QVariant::Map:
        error = pps_encoder_start_object(encoder, name);
        errorFunction = QStringLiteral("pps_encoder_start_object");
        if (error == PPS_ENCODER_OK) {
            encodeObject(encoder, data.toMap(), ok);
            error = pps_encoder_end_object(encoder);
            errorFunction = QStringLiteral("pps_encoder_end_object");
        }
        break;
    case QVariant::Invalid:
        error = pps_encoder_add_null(encoder, name);
        errorFunction = QStringLiteral("pps_encoder_add_null");
        break;
    default:
        qWarning() << "QPpsObjectPrivate::encodeData: the type of the parameter data is invalid";
        *ok = false;
        return;
    }

    if (error != PPS_ENCODER_OK) {
        qWarning() << "QPpsObjectPrivate::encodeData: " << errorFunction << " failed";
        *ok = false;
    } else {
        *ok = true;
    }
}
Example #25
0
bool QSQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
Example #26
0
void AVDecoder::setOptions(const QVariantHash &dict)
{
    DPTR_D(AVDecoder);
    d.options = dict;
    if (d.dict) {
        av_dict_free(&d.dict);
        d.dict = 0; //aready 0 in av_free
    }
    if (dict.isEmpty())
        return;
    // TODO: use QVariantMap only
    QVariant opt;
    if (dict.contains("avcodec"))
        opt = dict.value("avcodec");
    if (opt.type() == QVariant::Hash) {
        QVariantHash avcodec_dict = opt.toHash();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        // TODO: wrong if opt is empty
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toHash());
        QHashIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Hash: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap avcodec_dict = opt.toMap();
        // workaround for VideoDecoderFFmpeg. now it does not call av_opt_set_xxx, so set here in dict
        //if (dict.contains("FFmpeg"))
        //    avcodec_dict.unite(dict.value("FFmpeg").toMap());
        QMapIterator<QString, QVariant> i(avcodec_dict);
        while (i.hasNext()) {
            i.next();
            const QByteArray key(i.key().toLower().toUtf8());
            switch (i.value().type()) {
            case QVariant::Map: // for example "vaapi": {...}
                continue;
            case QVariant::Bool:
            case QVariant::UInt:
            case QVariant::Int: {
                // QVariant.toByteArray(): "true" or "false", can not recognized by avcodec
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toInt()), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toInt(), 0);
            }
                break;
            case QVariant::ULongLong:
            case QVariant::LongLong: {
                av_dict_set(&d.dict, key.constData(), QByteArray::number(i.value().toLongLong()).constData(), 0);
                if (d.codec_ctx)
                    av_opt_set_int(d.codec_ctx, key.constData(), i.value().toLongLong(), 0);
            }
                break;
            default:
                // avcodec key and value are in lower case
                av_dict_set(&d.dict, i.key().toLower().toUtf8().constData(), i.value().toByteArray().toLower().constData(), 0);
                break;
            }
            qDebug("avcodec option: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }
    if (name() == "avcodec")
        return;
    if (dict.contains(name()))
        opt = dict.value(name());
    else if (dict.contains(name().toLower()))
        opt = dict.value(name().toLower());
    else
        return;
    if (opt.type() == QVariant::Hash) {
        QVariantHash property_dict(opt.toHash());
        if (property_dict.isEmpty())
            return;
        QHashIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Hash) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    } else if (opt.type() == QVariant::Map) {
        QVariantMap property_dict(opt.toMap());
        if (property_dict.isEmpty())
            return;
        QMapIterator<QString, QVariant> i(property_dict);
        while (i.hasNext()) {
            i.next();
            if (i.value().type() == QVariant::Map) // for example "vaapi": {...}
                continue;
            setProperty(i.key().toUtf8().constData(), i.value());
            qDebug("decoder property: %s=>%s", i.key().toUtf8().constData(), i.value().toByteArray().constData());
        }
    }

}
Example #27
0
/*!
    Sets the \a newValue for \a option and returns \c true on success; \c false
    otherwise.

    \note If the option's associated type is \c quint8 or \c quint16 and the
    type of \a newValue is larger, the data will be truncated or conversation
    will fail.

    \table
        \header
            \li Key
            \li Description
        \row
            \li \l QModbusServer::DiagnosticRegister
            \li Sets the diagnostic register of the server in a device specific
                encoding to \a newValue. The default value preset is \c 0x0000.
                The bit values of the register need device specific documentation.
        \row
            \li \l QModbusServer::ExceptionStatusOffset
            \li Sets the exception status byte offset of the server to
                \a newValue which is the absolute offset address in the coils
                (0x register). Modbus register table starting with \c 0x0000h.
                The default value preset is \c 0x0000, using the exception
                status coils similar to Modicon 984 CPUs (coils 1-8).

                The function returns \c true if the coils register contains the
                8 bits required for storing and retrieving the status coils,
                otherwise \c false.
        \row
            \li \l QModbusServer::DeviceBusy
            \li Sets a flag that signals that the server is engaged in
                processing a long-duration program command. Valid values are
                \c 0x0000 (not busy) and \c 0xffff (busy).
                The default value preset is \c 0x0000.
        \row
            \li \l QModbusServer::AsciiInputDelimiter
            \li The \a newValue becomes the end of message delimiter for future
                Modbus ASCII messages. The default value preset is \c {\n}.
        \row
            \li \l QModbusServer::ListenOnlyMode
            \li Ss the server's listen only state to \a newValue. If listen only
                mode is set to \c true, messages are monitored but no response
                will be sent. The default value preset is \c false.
        \row
            \li \l QModbusServer::ServerIdentifier
            \li Sets the server's manufacturer identifier to \a newValue.
                Possible values are in the range of \c 0x00 to 0xff.
                The default value preset is \c 0x0a.
        \row
            \li \l QModbusServer::RunIndicatorStatus
            \li Sets the servers' run indicator status to \a newValue. This
                data is used as addendum by the \l QModbusPdu::ReportServerId
                function code. Valid values are \c 0x00 (OFF) and \c 0xff (ON).
                The default value preset is \c 0xff (ON).
        \row
            \li \l QModbusServer::AdditionalData
            \li Sets the server's additional data to \a newValue. This data is
                used as addendum by the \l QModbusPdu::ReportServerId function
                code. The maximum data size cannot exceed 249 bytes to match
                response message size restrictions.
                The default value preset is \c {Qt Modbus Server}.
        \row
            \li \l QModbusServer::UserOption
            \li Sets the value of a user option to \a newValue.

                \note For user options, it is up to the developer to decide
                which types to use and ensure that components use the correct
                types when accessing and setting values.
    \endtable
*/
bool QModbusServer::setValue(int option, const QVariant &newValue)
{
#define CHECK_INT_OR_UINT(val) \
    do { \
        if ((val.type() != QVariant::Int) && (val.type() != QVariant::UInt)) \
            return false; \
    } while (0)

    Q_D(QModbusServer);
    switch (option) {
    case DiagnosticRegister:
        CHECK_INT_OR_UINT(newValue);
        d->m_serverOptions.insert(option, newValue);
        return true;
    case ExceptionStatusOffset: {
        CHECK_INT_OR_UINT(newValue);
        const quint16 tmp = newValue.value<quint16>();
        QModbusDataUnit coils(QModbusDataUnit::Coils, tmp, 8);
        if (!data(&coils))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case DeviceBusy: {
        CHECK_INT_OR_UINT(newValue);
        const quint16 tmp = newValue.value<quint16>();
        if ((tmp != 0x0000) && (tmp != 0xffff))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case AsciiInputDelimiter: {
        CHECK_INT_OR_UINT(newValue);
        bool ok = false;
        if (newValue.toUInt(&ok) > 0xff || !ok)
            return false;
        d->m_serverOptions.insert(option, newValue);
        return true;
    }
    case ListenOnlyMode: {
        if (newValue.type() != QVariant::Bool)
            return false;
        d->m_serverOptions.insert(option, newValue);
        return true;
    }
    case ServerIdentifier:
        CHECK_INT_OR_UINT(newValue);
        d->m_serverOptions.insert(option, newValue);
        return true;
    case RunIndicatorStatus: {
        CHECK_INT_OR_UINT(newValue);
        const quint8 tmp = newValue.value<quint8>();
        if ((tmp != 0x00) && (tmp != 0xff))
            return false;
        d->m_serverOptions.insert(option, tmp);
        return true;
    }
    case AdditionalData: {
        if (newValue.type() != QVariant::ByteArray)
            return false;
        const QByteArray additionalData = newValue.toByteArray();
        if (additionalData.size() > 249)
            return false;
        d->m_serverOptions.insert(option, additionalData);
        return true;
    }
    default:
        break;
    };

    if (option < UserOption)
        return false;
    d->m_serverOptions.insert(option, newValue);
    return true;

#undef CHECK_INT_OR_UINT
}
Example #28
0
QVariant QSystemLocale::query(QueryType type, QVariant in) const
{
    QSystemLocaleData *d = qSystemLocaleData();
#if defined(Q_OS_QNX)
    QBBLocaleData *bbd = qbbLocaleData();
#endif
    const QLocale &lc_numeric = d->lc_numeric;
    const QLocale &lc_time = d->lc_time;
    const QLocale &lc_monetary = d->lc_monetary;
    const QLocale &lc_messages = d->lc_messages;

    switch (type) {
    case DecimalPoint:
        return lc_numeric.decimalPoint();
    case GroupSeparator:
        return lc_numeric.groupSeparator();
    case ZeroDigit:
        return lc_numeric.zeroDigit();
    case NegativeSign:
        return lc_numeric.negativeSign();
    case DateFormatLong:
        return lc_time.dateFormat(QLocale::LongFormat);
    case DateFormatShort:
        return lc_time.dateFormat(QLocale::ShortFormat);
    case TimeFormatLong:
        return lc_time.timeFormat(QLocale::LongFormat);
    case TimeFormatShort:
        return lc_time.timeFormat(QLocale::ShortFormat);
    case DayNameLong:
        return lc_time.dayName(in.toInt(), QLocale::LongFormat);
    case DayNameShort:
        return lc_time.dayName(in.toInt(), QLocale::ShortFormat);
    case MonthNameLong:
        return lc_time.monthName(in.toInt(), QLocale::LongFormat);
    case MonthNameShort:
        return lc_time.monthName(in.toInt(), QLocale::ShortFormat);
    case DateToStringLong:
        return lc_time.toString(in.toDate(), QLocale::LongFormat);
    case DateToStringShort:
        return lc_time.toString(in.toDate(), QLocale::ShortFormat);
    case TimeToStringLong:
        return lc_time.toString(in.toTime(), QLocale::LongFormat);
    case TimeToStringShort:
        return lc_time.toString(in.toTime(), QLocale::ShortFormat);
    case DateTimeFormatLong:
        return lc_time.dateTimeFormat(QLocale::LongFormat);
    case DateTimeFormatShort:
        return lc_time.dateTimeFormat(QLocale::ShortFormat);
    case DateTimeToStringLong:
        return lc_time.toString(in.toDateTime(), QLocale::LongFormat);
    case DateTimeToStringShort:
        return lc_time.toString(in.toDateTime(), QLocale::ShortFormat);
    case PositiveSign:
        return lc_numeric.positiveSign();
    case AMText:
        return lc_time.amText();
    case PMText:
        return lc_time.pmText();
    case FirstDayOfWeek:
        return lc_time.firstDayOfWeek();
    case CurrencySymbol:
        return lc_monetary.currencySymbol(QLocale::CurrencySymbolFormat(in.toUInt()));
    case CurrencyToString: {
        switch (in.type()) {
        case QVariant::Int:
            return lc_monetary.toCurrencyString(in.toInt());
        case QVariant::UInt:
            return lc_monetary.toCurrencyString(in.toUInt());
        case QVariant::Double:
            return lc_monetary.toCurrencyString(in.toDouble());
        case QVariant::LongLong:
            return lc_monetary.toCurrencyString(in.toLongLong());
        case QVariant::ULongLong:
            return lc_monetary.toCurrencyString(in.toULongLong());
        default:
            break;
        }
        return QString();
    }
    case MeasurementSystem: {
        const QString meas_locale = QString::fromLatin1(d->lc_measurement_var.constData(), d->lc_measurement_var.size());
        if (meas_locale.compare(QLatin1String("Metric"), Qt::CaseInsensitive) == 0)
            return QLocale::MetricSystem;
        if (meas_locale.compare(QLatin1String("Other"), Qt::CaseInsensitive) == 0)
            return QLocale::MetricSystem;
#if defined(Q_OS_QNX)
        return bbd->ppsMeasurement;
#endif
        return QVariant((int)QLocale(meas_locale).measurementSystem());
    }
    case UILanguages: {
        static QString languages = QString::fromLatin1(qgetenv("LANGUAGE"));
        if (!languages.isEmpty()) {
            QStringList lst = languages.split(QLatin1Char(':'));
            for (int i = 0; i < lst.size();) {
                const QString &name = lst.at(i);
                QString lang, script, cntry;
                if (name.isEmpty() || !qt_splitLocaleName(name, lang, script, cntry))
                    lst.removeAt(i);
                else
                    ++i;
            }
            return lst;
        }
        if (!d->lc_messages_var.isEmpty()) {
            QString lang, script, cntry;
            if (qt_splitLocaleName(QString::fromLatin1(d->lc_messages_var.constData(), d->lc_messages_var.size()),
                                lang, script, cntry)) {
                if (!cntry.length() && lang.length())
                    return QStringList(lang);
                return QStringList(lang % QLatin1Char('-') % cntry);
            }
        }
        return QVariant();
    }
    case StringToStandardQuotation:
        return lc_messages.quoteString(in.value<QStringRef>());
    case StringToAlternateQuotation:
        return lc_messages.quoteString(in.value<QStringRef>(), QLocale::AlternateQuotation);
    case ListToSeparatedString:
        return lc_messages.createSeparatedList(in.value<QStringList>());
    case LocaleChanged:
        d->updateLocale();
        break;
    default:
        break;
    }
    return QVariant();
}
Example #29
0
bool qgsVariantLessThan( const QVariant& lhs, const QVariant& rhs )
{
  // invalid < NULL < any value
  if ( !lhs.isValid() )
    return rhs.isValid();
  else if ( lhs.isNull() )
    return rhs.isValid() && !rhs.isNull();
  else if ( !rhs.isValid() || rhs.isNull() )
    return false;

  switch ( lhs.type() )
  {
    case QVariant::Int:
      return lhs.toInt() < rhs.toInt();
    case QVariant::UInt:
      return lhs.toUInt() < rhs.toUInt();
    case QVariant::LongLong:
      return lhs.toLongLong() < rhs.toLongLong();
    case QVariant::ULongLong:
      return lhs.toULongLong() < rhs.toULongLong();
    case QVariant::Double:
      return lhs.toDouble() < rhs.toDouble();
    case QVariant::Char:
      return lhs.toChar() < rhs.toChar();
    case QVariant::Date:
      return lhs.toDate() < rhs.toDate();
    case QVariant::Time:
      return lhs.toTime() < rhs.toTime();
    case QVariant::DateTime:
      return lhs.toDateTime() < rhs.toDateTime();
    case QVariant::Bool:
      return lhs.toBool() < rhs.toBool();

    case QVariant::List:
    {
      const QList<QVariant> &lhsl = lhs.toList();
      const QList<QVariant> &rhsl = rhs.toList();

      int i, n = qMin( lhsl.size(), rhsl.size() );
      for ( i = 0; i < n && lhsl[i].type() == rhsl[i].type() && lhsl[i].isNull() == rhsl[i].isNull() && lhsl[i] == rhsl[i]; i++ )
        ;

      if ( i == n )
        return lhsl.size() < rhsl.size();
      else
        return qgsVariantLessThan( lhsl[i], rhsl[i] );
    }

    case QVariant::StringList:
    {
      const QStringList &lhsl = lhs.toStringList();
      const QStringList &rhsl = rhs.toStringList();

      int i, n = qMin( lhsl.size(), rhsl.size() );
      for ( i = 0; i < n && lhsl[i] == rhsl[i]; i++ )
        ;

      if ( i == n )
        return lhsl.size() < rhsl.size();
      else
        return lhsl[i] < rhsl[i];
    }

    default:
      return QString::localeAwareCompare( lhs.toString(), rhs.toString() ) < 0;
  }
}
Example #30
0
void TestQgsField::convertCompatible()
{
  //test string field
  QgsField stringField( QStringLiteral( "string" ), QVariant::String, QStringLiteral( "string" ) );

  QVariant stringVar( "test string" );
  QVERIFY( stringField.convertCompatible( stringVar ) );
  QCOMPARE( stringVar.toString(), QString( "test string" ) );
  QVariant nullString = QVariant( QVariant::String );
  QVERIFY( stringField.convertCompatible( nullString ) );
  QCOMPARE( nullString.type(), QVariant::String );
  QVERIFY( nullString.isNull() );
  QVariant intVar( 5 );
  QVERIFY( stringField.convertCompatible( intVar ) );
  QCOMPARE( intVar.type(), QVariant::String );
  QCOMPARE( intVar, QVariant( "5" ) );
  QVariant nullInt = QVariant( QVariant::Int );
  QVERIFY( stringField.convertCompatible( nullInt ) );
  QCOMPARE( nullInt.type(), QVariant::String );
  QVERIFY( nullInt.isNull() );
  QVariant doubleVar( 1.25 );
  QVERIFY( stringField.convertCompatible( doubleVar ) );
  QCOMPARE( doubleVar.type(), QVariant::String );
  QCOMPARE( doubleVar, QVariant( "1.25" ) );
  QVariant nullDouble = QVariant( QVariant::Double );
  QVERIFY( stringField.convertCompatible( nullDouble ) );
  QCOMPARE( nullDouble.type(), QVariant::String );
  QVERIFY( nullDouble.isNull() );

  //test double
  QgsField doubleField( QStringLiteral( "double" ), QVariant::Double, QStringLiteral( "double" ) );

  stringVar = QVariant( "test string" );
  QVERIFY( !doubleField.convertCompatible( stringVar ) );
  QCOMPARE( stringVar.type(), QVariant::Double );
  QVERIFY( stringVar.isNull() );
  nullString = QVariant( QVariant::String );
  QVERIFY( doubleField.convertCompatible( nullString ) );
  QCOMPARE( nullString.type(), QVariant::Double );
  QVERIFY( nullString.isNull() );
  intVar = QVariant( 5 );
  QVERIFY( doubleField.convertCompatible( intVar ) );
  QCOMPARE( intVar.type(), QVariant::Double );
  QCOMPARE( intVar, QVariant( 5.0 ) );
  nullInt = QVariant( QVariant::Int );
  QVERIFY( doubleField.convertCompatible( nullInt ) );
  QCOMPARE( nullInt.type(), QVariant::Double );
  QVERIFY( nullInt.isNull() );
  doubleVar = QVariant( 1.25 );
  QVERIFY( doubleField.convertCompatible( doubleVar ) );
  QCOMPARE( doubleVar.type(), QVariant::Double );
  QCOMPARE( doubleVar, QVariant( 1.25 ) );
  nullDouble = QVariant( QVariant::Double );
  QVERIFY( doubleField.convertCompatible( nullDouble ) );
  QCOMPARE( nullDouble.type(), QVariant::Double );
  QVERIFY( nullDouble.isNull() );

  //test special rules

  //conversion of double to int
  QgsField intField( QStringLiteral( "int" ), QVariant::Int, QStringLiteral( "int" ) );
  //small double, should be rounded
  QVariant smallDouble( 45.7 );
  QVERIFY( intField.convertCompatible( smallDouble ) );
  QCOMPARE( smallDouble.type(), QVariant::Int );
  QCOMPARE( smallDouble, QVariant( 46 ) );
  QVariant negativeSmallDouble( -9345.754534525235235 );
  QVERIFY( intField.convertCompatible( negativeSmallDouble ) );
  QCOMPARE( negativeSmallDouble.type(), QVariant::Int );
  QCOMPARE( negativeSmallDouble, QVariant( -9346 ) );
  //large double, cannot be converted
  QVariant largeDouble( 9999999999.99 );
  QVERIFY( !intField.convertCompatible( largeDouble ) );
  QCOMPARE( largeDouble.type(), QVariant::Int );
  QVERIFY( largeDouble.isNull() );

  //conversion of string double value to int
  QVariant notNumberString( "notanumber" );
  QVERIFY( !intField.convertCompatible( notNumberString ) );
  QCOMPARE( notNumberString.type(), QVariant::Int );
  QVERIFY( notNumberString.isNull() );
  //small double, should be rounded
  QVariant smallDoubleString( "45.7" );
  QVERIFY( intField.convertCompatible( smallDoubleString ) );
  QCOMPARE( smallDoubleString.type(), QVariant::Int );
  QCOMPARE( smallDoubleString, QVariant( 46 ) );
  QVariant negativeSmallDoubleString( "-9345.754534525235235" );
  QVERIFY( intField.convertCompatible( negativeSmallDoubleString ) );
  QCOMPARE( negativeSmallDoubleString.type(), QVariant::Int );
  QCOMPARE( negativeSmallDoubleString, QVariant( -9346 ) );
  //large double, cannot be converted
  QVariant largeDoubleString( "9999999999.99" );
  QVERIFY( !intField.convertCompatible( largeDoubleString ) );
  QCOMPARE( largeDoubleString.type(), QVariant::Int );
  QVERIFY( largeDoubleString.isNull() );

  //conversion of longlong to int
  QVariant longlong( 99999999999999999LL );
  QVERIFY( !intField.convertCompatible( longlong ) );
  QCOMPARE( longlong.type(), QVariant::Int );
  QVERIFY( longlong.isNull() );
  QVariant smallLonglong( 99LL );
  QVERIFY( intField.convertCompatible( smallLonglong ) );
  QCOMPARE( smallLonglong.type(), QVariant::Int );
  QCOMPARE( smallLonglong, QVariant( 99 ) );
  //conversion of longlong to longlong field
  QgsField longlongField( QStringLiteral( "long" ), QVariant::LongLong, QStringLiteral( "longlong" ) );
  longlong = QVariant( 99999999999999999LL );
  QVERIFY( longlongField.convertCompatible( longlong ) );
  QCOMPARE( longlong.type(), QVariant::LongLong );
  QCOMPARE( longlong, QVariant( 99999999999999999LL ) );

  //string representation of an int
  QVariant stringInt( "123456" );
  QVERIFY( intField.convertCompatible( stringInt ) );
  QCOMPARE( stringInt.type(), QVariant::Int );
  QCOMPARE( stringInt, QVariant( 123456 ) );
  // now with group separator for english locale
  stringInt = QVariant( "123,456" );
  QVERIFY( intField.convertCompatible( stringInt ) );
  QCOMPARE( stringInt.type(), QVariant::Int );
  QCOMPARE( stringInt, QVariant( "123456" ) );

  //string representation of a longlong
  QVariant stringLong( "99999999999999999" );
  QVERIFY( longlongField.convertCompatible( stringLong ) );
  QCOMPARE( stringLong.type(), QVariant::LongLong );
  QCOMPARE( stringLong, QVariant( 99999999999999999LL ) );
  // now with group separator for english locale
  stringLong = QVariant( "99,999,999,999,999,999" );
  QVERIFY( longlongField.convertCompatible( stringLong ) );
  QCOMPARE( stringLong.type(), QVariant::LongLong );
  QCOMPARE( stringLong, QVariant( 99999999999999999LL ) );


  //string representation of a double
  QVariant stringDouble( "123456.012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 123456.012345 ) );
  // now with group separator for english locale
  stringDouble = QVariant( "1,223,456.012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 1223456.012345 ) );
  // This should not convert
  stringDouble = QVariant( "1.223.456,012345" );
  QVERIFY( ! doubleField.convertCompatible( stringDouble ) );


  //double with precision
  QgsField doubleWithPrecField( QStringLiteral( "double" ), QVariant::Double, QStringLiteral( "double" ), 10, 3 );
  doubleVar = QVariant( 10.12345678 );
  //note - this returns true!
  QVERIFY( doubleWithPrecField.convertCompatible( doubleVar ) );
  QCOMPARE( doubleVar.type(), QVariant::Double );
  QCOMPARE( doubleVar.toDouble(), 10.123 );

  //truncating string length
  QgsField stringWithLen( QStringLiteral( "string" ), QVariant::String, QStringLiteral( "string" ), 3 );
  stringVar = QVariant( "longstring" );
  QVERIFY( !stringWithLen.convertCompatible( stringVar ) );
  QCOMPARE( stringVar.type(), QVariant::String );
  QCOMPARE( stringVar.toString(), QString( "lon" ) );


  /////////////////////////////////////////////////////////
  // German locale tests

  //double with ',' as decimal separator for German locale
  QLocale::setDefault( QLocale::German );
  QVariant doubleCommaVar( "1,2345" );
  QVERIFY( doubleField.convertCompatible( doubleCommaVar ) );
  QCOMPARE( doubleCommaVar.type(), QVariant::Double );
  QCOMPARE( doubleCommaVar.toString(), QString( "1.2345" ) );

  //string representation of an int
  stringInt = QVariant( "123456" );
  QVERIFY( intField.convertCompatible( stringInt ) );
  QCOMPARE( stringInt.type(), QVariant::Int );
  QCOMPARE( stringInt, QVariant( 123456 ) );
  // now with group separator for german locale
  stringInt = QVariant( "123.456" );
  QVERIFY( intField.convertCompatible( stringInt ) );
  QCOMPARE( stringInt.type(), QVariant::Int );
  QCOMPARE( stringInt, QVariant( "123456" ) );

  //string representation of a longlong
  stringLong = QVariant( "99999999999999999" );
  QVERIFY( longlongField.convertCompatible( stringLong ) );
  QCOMPARE( stringLong.type(), QVariant::LongLong );
  QCOMPARE( stringLong, QVariant( 99999999999999999LL ) );
  // now with group separator for german locale
  stringLong = QVariant( "99.999.999.999.999.999" );
  QVERIFY( longlongField.convertCompatible( stringLong ) );
  QCOMPARE( stringLong.type(), QVariant::LongLong );
  QCOMPARE( stringLong, QVariant( 99999999999999999LL ) );

  //string representation of a double
  stringDouble = QVariant( "123456,012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 123456.012345 ) );
  // For doubles we also want to accept dot as a decimal point
  stringDouble = QVariant( "123456.012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 123456.012345 ) );
  // now with group separator for german locale
  stringDouble = QVariant( "1.223.456,012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 1223456.012345 ) );
  // Be are good citizens and we also accept english locale
  stringDouble = QVariant( "1,223,456.012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 1223456.012345 ) );

  // Test that wrongly formatted decimal separator are also accepted
  QLocale::setDefault( QLocale::German );
  stringDouble = QVariant( "12.23.456,012345" );
  QVERIFY( doubleField.convertCompatible( stringDouble ) );
  QCOMPARE( stringDouble.type(), QVariant::Double );
  QCOMPARE( stringDouble, QVariant( 1223456.012345 ) );

}