void QwtPlotPropertySetDialog::onPropertyValueChanged(QtProperty * property, const QVariant & value) { if(!m_enableSet) return; int id = m_property_id.getPropertyID(property); if (id < ID_CurveIDBase) { switch(id) { case ID_PlotTitle: m_plot->setTitle(value.toString()); return; case ID_PlotFooter: m_plot->setFooter(value.toString()); return; case ID_PlotCanvasBackground: m_plot->setCanvasBackground(QBrush(value.value<QColor>())); return; case ID_PlotEnableZoomerScroll: m_plot->enableZoomerScroll(value.toBool()); return; case ID_PlotAxisSet: setAxisEnable(value.toInt()); return; case ID_XBottomScale: setAxisScaleDrawStyle(QwtPlot::xBottom,value); return; case ID_XTopScale: setAxisScaleDrawStyle(QwtPlot::xTop,value); return; case ID_YLeftScale: setAxisScaleDrawStyle(QwtPlot::yLeft,value); return; case ID_YRightScale: setAxisScaleDrawStyle(QwtPlot::yRight,value); return; case ID_XBottomDateScaleType: m_plot->setAxisDateFormat(QwtPlot::xBottom,ChartWave_qwt::AxisDateScaleType(value.toInt())); return; case ID_XTopDateScaleType: m_plot->setAxisDateFormat(QwtPlot::xTop,ChartWave_qwt::AxisDateScaleType(value.toInt())); return; case ID_YLeftDateScaleType: m_plot->setAxisDateFormat(QwtPlot::yLeft,ChartWave_qwt::AxisDateScaleType(value.toInt())); return; case ID_YRightDateScaleType: m_plot->setAxisDateFormat(QwtPlot::yRight,ChartWave_qwt::AxisDateScaleType(value.toInt())); return; case ID_XBottomInterval: case ID_XTopInterval: case ID_YLeftInterval: case ID_YRightInterval: setAxisScale(id,value.toPointF()); return; case ID_XBottomTitle: case ID_XTopTitle: case ID_YLeftTitle: case ID_YRightTitle: setAxisTitle(id,value.toString()); return; case ID_XBottomLabelRotation: case ID_XTopLabelRotation: case ID_YLeftLabelRotation: case ID_YRightLabelRotation: setAxislabelRotation(id,value.toDouble()); return; } } else { QwtPlotCurve* cur = getCurvePtr(id); if(!cur) return; const int propertyID = getCurvePropertyID(id); if (ID_CurveTitle == propertyID) { cur->setTitle(value.toString()); return; } QPen newPen(cur->pen()); switch (propertyID) { case ID_CurveColore: newPen.setColor(value.value<QColor>()); break; case ID_CurveWidth: newPen.setWidth(value.toInt()); break; case ID_CurvePenStyle: newPen.setStyle(order2penStyle(value.toInt())); break; } cur->setPen(newPen); } }
static QBitmap qwtBorderMask( const QWidget *canvas, const QSize &size ) { const QRect r( 0, 0, size.width(), size.height() ); QPainterPath borderPath; ( void )QMetaObject::invokeMethod( const_cast< QWidget *>( canvas ), "borderPath", Qt::DirectConnection, Q_RETURN_ARG( QPainterPath, borderPath ), Q_ARG( QRect, r ) ); if ( borderPath.isEmpty() ) { if ( canvas->contentsRect() == canvas->rect() ) return QBitmap(); QBitmap mask( size ); mask.fill( Qt::color0 ); QPainter painter( &mask ); painter.fillRect( canvas->contentsRect(), Qt::color1 ); return mask; } QImage image( size, QImage::Format_ARGB32_Premultiplied ); image.fill( Qt::color0 ); QPainter painter( &image ); painter.setClipPath( borderPath ); painter.fillRect( r, Qt::color1 ); // now erase the frame painter.setCompositionMode( QPainter::CompositionMode_DestinationOut ); if ( canvas->testAttribute(Qt::WA_StyledBackground ) ) { QStyleOptionFrame opt; opt.initFrom(canvas); opt.rect = r; canvas->style()->drawPrimitive( QStyle::PE_Frame, &opt, &painter, canvas ); } else { const QVariant borderRadius = canvas->property( "borderRadius" ); const QVariant frameWidth = canvas->property( "frameWidth" ); if ( borderRadius.type() == QVariant::Double && frameWidth.type() == QVariant::Int ) { const double br = borderRadius.toDouble(); const int fw = frameWidth.toInt(); if ( br > 0.0 && fw > 0 ) { painter.setPen( QPen( Qt::color1, fw ) ); painter.setBrush( Qt::NoBrush ); painter.setRenderHint( QPainter::Antialiasing, true ); painter.drawPath( borderPath ); } } } painter.end(); const QImage mask = image.createMaskFromColor( QColor( Qt::color1 ).rgb(), Qt::MaskOutColor ); return QBitmap::fromImage( mask ); }
QT_BEGIN_NAMESPACE static void copyArgument(void *to, int id, const QVariant &arg) { if (id == arg.userType()) { switch (id) { case QVariant::Bool: *reinterpret_cast<bool *>(to) = arg.toBool(); return; case QMetaType::UChar: *reinterpret_cast<uchar *>(to) = arg.value<uchar>(); return; case QMetaType::Short: *reinterpret_cast<short *>(to) = arg.value<short>(); return; case QMetaType::UShort: *reinterpret_cast<ushort *>(to) = arg.value<ushort>(); return; case QVariant::Int: *reinterpret_cast<int *>(to) = arg.toInt(); return; case QVariant::UInt: *reinterpret_cast<uint *>(to) = arg.toUInt(); return; case QVariant::LongLong: *reinterpret_cast<qlonglong *>(to) = arg.toLongLong(); return; case QVariant::ULongLong: *reinterpret_cast<qulonglong *>(to) = arg.toULongLong(); return; case QVariant::Double: *reinterpret_cast<double *>(to) = arg.toDouble(); return; case QVariant::String: *reinterpret_cast<QString *>(to) = arg.toString(); return; case QVariant::ByteArray: *reinterpret_cast<QByteArray *>(to) = arg.toByteArray(); return; case QVariant::StringList: *reinterpret_cast<QStringList *>(to) = arg.toStringList(); return; } if (id == QDBusMetaTypeId::variant) { *reinterpret_cast<QDBusVariant *>(to) = arg.value<QDBusVariant>(); return; } else if (id == QDBusMetaTypeId::objectpath) { *reinterpret_cast<QDBusObjectPath *>(to) = arg.value<QDBusObjectPath>(); return; } else if (id == QDBusMetaTypeId::signature) { *reinterpret_cast<QDBusSignature *>(to) = arg.value<QDBusSignature>(); return; } // those above are the only types possible // the demarshaller code doesn't demarshall anything else qFatal("Found a decoded basic type in a D-Bus reply that shouldn't be there"); } // if we got here, it's either an un-dermarshalled type or a mismatch if (arg.userType() != QDBusMetaTypeId::argument) { // it's a mismatch //qWarning? return; } // is this type registered? const char *userSignature = QDBusMetaType::typeToSignature(id); if (!userSignature || !*userSignature) { // type not registered //qWarning? return; } // is it the same signature? QDBusArgument dbarg = arg.value<QDBusArgument>(); if (dbarg.currentSignature() != QLatin1String(userSignature)) { // not the same signature, another mismatch //qWarning? return; } // we can demarshall QDBusMetaType::demarshall(dbarg, id, to); }
int QgsTINInterpolator::insertData( QgsFeature* f, bool zCoord, int attr, InputType type ) { if ( !f ) { return 1; } QgsGeometry* g = f->geometry(); { if ( !g ) { return 2; } } //check attribute value double attributeValue = 0; bool attributeConversionOk = false; if ( !zCoord ) { QVariant attributeVariant = f->attribute( attr ); if ( !attributeVariant.isValid() ) //attribute not found, something must be wrong (e.g. NULL value) { return 3; } attributeValue = attributeVariant.toDouble( &attributeConversionOk ); if ( !attributeConversionOk || qIsNaN( attributeValue ) ) //don't consider vertices with attributes like 'nan' for the interpolation { return 4; } } //parse WKB. It is ugly, but we cannot use the methods with QgsPoint because they don't contain z-values for 25D types bool hasZValue = false; double x, y, z; QgsConstWkbPtr currentWkbPtr( g->asWkb() + 1 + sizeof( int ) ); //maybe a structure or break line Line3D* line = 0; QGis::WkbType wkbType = g->wkbType(); switch ( wkbType ) { case QGis::WKBPoint25D: hasZValue = true; case QGis::WKBPoint: { currentWkbPtr >> x >> y; if ( zCoord && hasZValue ) { currentWkbPtr >> z; } else { z = attributeValue; } Point3D* thePoint = new Point3D( x, y, z ); if ( mTriangulation->addPoint( thePoint ) == -100 ) { return -1; } break; }
bool cmpDoubleVariant( const QVariant& a, const QVariant& b ) { return a.toDouble( ) < b.toDouble( ); }
QVariant SketchConstraintsSolver::solve() { this->solved = false; if(this->sketch == Q_NULLPTR) { return "Sketch is null"; } /* * get the mm/pixel scale */ QVariant isScaleSet; bool isIsMmPerPixelScaleSetCallWorks = QMetaObject::invokeMethod( this->sketch, "isMmPerPixelScaleSet", Q_RETURN_ARG(QVariant, isScaleSet) ); if(!isIsMmPerPixelScaleSetCallWorks) { return "Cannot check if the scale is set"; } if(!isScaleSet.toBool()) { return "Cannot apply constraints without scale"; } QVariant mmPerPixelScale; bool isGetMmPerPixelScaleCallWorks = QMetaObject::invokeMethod( this->sketch, "getMmPerPixelScale", Q_RETURN_ARG(QVariant, mmPerPixelScale) ); if(!isGetMmPerPixelScaleCallWorks) { return "Cannot retrieve the scale"; } double pixelPerMmScale = 1.0 / mmPerPixelScale.toDouble(); // clean old computation this->points.clear(); this->lines.clear(); this->constraints.clear(); bool first = false; // extract sketch data QVariantMap store = this->sketch->property("store").value<QVariantMap>(); QVariantList points = store["points"].value<QVariantList>(); QVariantList lines = store["lines"].value<QVariantList>(); foreach(QVariant item, points) { QObject* point = item.value<QObject*>(); if(first) { this->origin = point->property("start").value<QVector2D>(); first = false; } QVector2D start = point->property("start").value<QVector2D>(); QSharedPointer<ConstrainedPoint> newPoint(new ConstrainedPoint( start.x() - this->origin.x(), start.y() - this->origin.y(), point )); this->points[newPoint->identifier().toInt()] = newPoint; }
double Options::zoomLevel() const { QVariant zoom = settings_.value(QString::fromUtf8("view.zoomLevel"), 1.0); return zoom.toDouble(); }
QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDepth) const { if (property.isBindingProperty()) { return property.toBindingProperty().expression(); } else if (property.isSignalHandlerProperty()) { return property.toSignalHandlerProperty().source(); } else if (property.isNodeProperty()) { return toQml(property.toNodeProperty().modelNode(), indentDepth); } else if (property.isNodeListProperty()) { const QList<ModelNode> nodes = property.toNodeListProperty().toModelNodeList(); if (property.isDefaultProperty()) { QString result; for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1String("\n\n"); result += QString(indentDepth, QLatin1Char(' ')); result += toQml(nodes.at(i), indentDepth); } return result; } else { QString result = QLatin1String("["); const int arrayContentDepth = indentDepth + 4; const QString arrayContentIndentation(arrayContentDepth, QLatin1Char(' ')); for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1Char(','); result += QLatin1Char('\n'); result += arrayContentIndentation; result += toQml(nodes.at(i), arrayContentDepth); } return result + QLatin1Char(']'); } } else if (property.isVariantProperty()) { const VariantProperty variantProperty = property.toVariantProperty(); const QVariant value = variantProperty.value(); const QString stringValue = value.toString(); if (property.name() == "id") return stringValue; if (false) { } if (variantProperty.parentModelNode().metaInfo().isValid() && variantProperty.parentModelNode().metaInfo().propertyIsEnumType(variantProperty.name())) { return variantProperty.parentModelNode().metaInfo().propertyEnumScope(variantProperty.name()) + '.' + stringValue; } else { switch (value.type()) { case QVariant::Bool: if (value.value<bool>()) return QLatin1String("true"); else return QLatin1String("false"); case QVariant::Color: return QString(QLatin1String("\"%1\"")).arg(properColorName(value.value<QColor>())); case QVariant::Double: return doubleToString(value.toDouble()); case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: return stringValue; default: return QString(QLatin1String("\"%1\"")).arg(escape(stringValue)); } } } else { Q_ASSERT("Unknown property type"); return QString(); } }
void MDNullableDoubleSpinBox::setVariantValue(const QVariant &value) { setValue(value.toDouble()); }
QVariant LocaleModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || role != Qt::DisplayRole && role != Qt::EditRole && role != Qt::ToolTipRole || index.column() >= g_model_cols || index.row() >= g_locale_list_count + 2) return QVariant(); QVariant data; if (index.column() < g_model_cols - 1) data = m_data_list.at(index.column()); if (index.row() == 0) { if (role == Qt::ToolTipRole) return QVariant(); switch (index.column()) { case 0: return data.toDouble(); case 1: return data.toDate(); case 2: return data.toDate(); case 3: return data.toTime(); case 4: return data.toTime(); case 5: return QVariant(); default: break; } } else { QLocale locale; if (index.row() == 1) { locale = QLocale::system(); } else { LocaleListItem item = g_locale_list[index.row() - 2]; locale = QLocale((QLocale::Language)item.language, (QLocale::Country)item.country); } switch (index.column()) { case 0: if (role == Qt::ToolTipRole) return QVariant(); return locale.toString(data.toDouble()); case 1: if (role == Qt::ToolTipRole) return locale.dateFormat(QLocale::LongFormat); return locale.toString(data.toDate(), QLocale::LongFormat); case 2: if (role == Qt::ToolTipRole) return locale.dateFormat(QLocale::ShortFormat); return locale.toString(data.toDate(), QLocale::ShortFormat); case 3: if (role == Qt::ToolTipRole) return locale.timeFormat(QLocale::LongFormat); return locale.toString(data.toTime(), QLocale::LongFormat); case 4: if (role == Qt::ToolTipRole) return locale.timeFormat(QLocale::ShortFormat); return locale.toString(data.toTime(), QLocale::ShortFormat); case 5: if (role == Qt::ToolTipRole) return QVariant(); return locale.name(); default: break; } } return QVariant(); }
bool QDBusMarshaller::appendVariantInternal(const QVariant &arg) { int id = arg.userType(); if (id == QVariant::Invalid) { qWarning("QDBusMarshaller: cannot add an invalid QVariant"); error(); return false; } // intercept QDBusArgument parameters here if (id == qMetaTypeId<QDBusArgument>()) { QDBusArgument dbusargument = qvariant_cast<QDBusArgument>(arg); QDBusArgumentPrivate *d = QDBusArgumentPrivate::d(dbusargument); if (!d->message) return false; // can't append this one... QDBusDemarshaller demarshaller; demarshaller.message = q_dbus_message_ref(d->message); if (d->direction == Demarshalling) { // it's demarshalling; just copy demarshaller.iterator = static_cast<QDBusDemarshaller *>(d)->iterator; } else { // it's marshalling; start over if (!q_dbus_message_iter_init(demarshaller.message, &demarshaller.iterator)) return false; // error! } return appendCrossMarshalling(&demarshaller); } const char *signature = QDBusMetaType::typeToSignature( QVariant::Type(id) ); if (!signature) { qWarning("QDBusMarshaller: type `%s' (%d) is not registered with D-BUS. " "Use qDBusRegisterMetaType to register it", QVariant::typeToName( QVariant::Type(id) ), id); error(); return false; } switch (*signature) { #ifdef __OPTIMIZE__ case DBUS_TYPE_BYTE: case DBUS_TYPE_BOOLEAN: case DBUS_TYPE_INT16: case DBUS_TYPE_UINT16: case DBUS_TYPE_INT32: case DBUS_TYPE_UINT32: case DBUS_TYPE_INT64: case DBUS_TYPE_UINT64: case DBUS_TYPE_DOUBLE: qIterAppend(&iterator, ba, *signature, arg.constData()); return true; case DBUS_TYPE_STRING: case DBUS_TYPE_OBJECT_PATH: case DBUS_TYPE_SIGNATURE: { const QByteArray data = reinterpret_cast<const QString *>(arg.constData())->toUtf8(); const char *rawData = data.constData(); qIterAppend(&iterator, ba, *signature, &rawData); return true; } #else case DBUS_TYPE_BYTE: append( qvariant_cast<uchar>(arg) ); return true; case DBUS_TYPE_BOOLEAN: append( arg.toBool() ); return true; case DBUS_TYPE_INT16: append( qvariant_cast<short>(arg) ); return true; case DBUS_TYPE_UINT16: append( qvariant_cast<ushort>(arg) ); return true; case DBUS_TYPE_INT32: append( static_cast<dbus_int32_t>(arg.toInt()) ); return true; case DBUS_TYPE_UINT32: append( static_cast<dbus_uint32_t>(arg.toUInt()) ); return true; case DBUS_TYPE_INT64: append( arg.toLongLong() ); return true; case DBUS_TYPE_UINT64: append( arg.toULongLong() ); return true; case DBUS_TYPE_DOUBLE: append( arg.toDouble() ); return true; case DBUS_TYPE_STRING: append( arg.toString() ); return true; case DBUS_TYPE_OBJECT_PATH: append( qvariant_cast<QDBusObjectPath>(arg) ); return true; case DBUS_TYPE_SIGNATURE: append( qvariant_cast<QDBusSignature>(arg) ); return true; #endif // compound types: case DBUS_TYPE_VARIANT: // nested QVariant return append( qvariant_cast<QDBusVariant>(arg) ); case DBUS_TYPE_ARRAY: // could be many things // find out what kind of array it is switch (arg.type()) { case QVariant::StringList: append( arg.toStringList() ); return true; case QVariant::ByteArray: append( arg.toByteArray() ); return true; default: ; // fall through } // fall through case DBUS_TYPE_STRUCT: case DBUS_STRUCT_BEGIN_CHAR: return appendRegisteredType( arg ); case DBUS_TYPE_DICT_ENTRY: case DBUS_DICT_ENTRY_BEGIN_CHAR: qFatal("QDBusMarshaller::appendVariantInternal got a DICT_ENTRY!"); return false; default: qWarning("QDBusMarshaller::appendVariantInternal: Found unknown D-BUS type '%s'", signature); return false; } return true; }
bool QSymSQLResult::exec() { if (d->prepareCalled == false) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Statement is not prepared"), QSqlError::StatementError, KErrGeneral)); return false; } const QVector<QVariant> values = boundValues(); d->skippedStatus = false; d->skipRow = false; setAt(QSql::BeforeFirstRow); setLastError(QSqlError()); int res = d->stmt.Reset(); if (res != KErrNone) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Unable to reset statement"), QSqlError::StatementError, res)); d->finalize(); return false; } TPtrC tmp; TInt paramCount = 0; while (d->stmt.ParamName(paramCount, tmp) == KErrNone) paramCount++; if (paramCount == values.count()) { for (int i = 0; i < paramCount; ++i) { res = KErrNone; const QVariant value = values.at(i); if (value.isNull()) { res = d->stmt.BindNull(i); //replaced i + 1 with i } else { switch (value.type()) { case QVariant::ByteArray: { const QByteArray *ba = static_cast<const QByteArray*>(value.constData()); TPtrC8 data(reinterpret_cast<const TUint8 *>(ba->constData()), ba->length()); res = d->stmt.BindBinary(i, data); //replaced i + 1 with i break; } case QVariant::Int: res = d->stmt.BindInt(i, value.toInt()); //replaced i + 1 with i break; case QVariant::Double: res = d->stmt.BindReal(i, value.toDouble()); //replaced i + 1 with i break; case QVariant::UInt: case QVariant::LongLong: res = d->stmt.BindReal(i, value.toLongLong()); //replaced i + 1 with i break; case QVariant::String: { // lifetime of string == lifetime of its qvariant const QString *str = static_cast<const QString*>(value.constData()); res = d->stmt.BindText(i, qt_QString2TPtrC(*str)); // replaced i + 1 with i break; } default: { QString str = value.toString(); res = d->stmt.BindText(i, qt_QString2TPtrC(str)); //replaced i + 1 with i break; } } } if (res != KErrNone) { setLastError(qMakeError(d->access, QCoreApplication::translate("QSymSQLResult", "Unable to bind parameters"), QSqlError::StatementError, res)); d->finalize(); return false; } } } else { setLastError(QSqlError(QCoreApplication::translate("QSymSQLResult", "Parameter count mismatch"), QString(), QSqlError::StatementError)); return false; } d->skippedStatus = d->fetchNext(true); if (lastError().isValid()) { setSelect(false); setActive(false); return false; } if (d->stmt.ColumnCount() > 0) { //If there is something, it has to be select setSelect(true); } else { //If there isn't it might be just bad query, let's check manually whether we can find SELECT QString query = this->lastQuery(); query = query.trimmed(); query = query.toLower(); //Just check whether there is one in the beginning, don't know if this is enough //Comments should be at the end of line if those are passed //For some reason, case insensitive indexOf didn't work for me if (query.indexOf(QLatin1String("select")) == 0) { setSelect(true); } else { setSelect(false); } } setActive(true); return true; }
QString JSON::stringify(QVariant v){ if (v.isNull()){ return QLatin1String("null"); } switch (v.type()) { case QVariant::Bool: return v.toBool()?QLatin1String("true"):QLatin1String("false"); break; case QVariant::ULongLong: case QVariant::UInt: return QString::number(v.toULongLong()); break; case QVariant::LongLong: case QVariant::Int: return QString::number(v.toLongLong()); break; case QVariant::Double: return QString::number(v.toDouble()); break; case QVariant::Map: { QString r=QLatin1String("{"); QMap<QString, QVariant> map = v.toMap(); QMapIterator<QString, QVariant> i(map); while (i.hasNext()){ i.next(); r+=QLatin1String("\"")+i.key()+ QLatin1String("\":") +stringify(i.value())+QLatin1String(","); } if(r.length()>1) r.chop(1); r+=QLatin1String("}"); return r; } break; #if QT_VERSION >= 0x040500 case QVariant::Hash: { QString r=QLatin1String("{"); QHash<QString, QVariant> map = v.toHash(); QHashIterator<QString, QVariant> i(map); while (i.hasNext()){ i.next(); r+=QLatin1String("\"")+i.key()+QLatin1String("\":")+stringify(i.value())+QLatin1String(","); } if(r.length()>1) r.chop(1); r+=QLatin1String("}"); return r; } break; #endif case QVariant::StringList: { QString r=QLatin1String("["); QStringList l = v.toStringList(); foreach(QString i, l){ r+=QLatin1String("\"")+i+QLatin1String("\","); } if(r.length()>1) r.chop(1); r+=QLatin1String("]"); return r; } case QVariant::List: { QString r=QLatin1String("["); QVariantList l = v.toList(); foreach(QVariant i, l){ r+=stringify(i)+QLatin1String(","); } if(r.length()>1) r.chop(1); r+=QLatin1String("]"); return r; }
enum SetResponse taxDetail::set(const ParameterList & pParams ) { XDialog::set(pParams); QVariant param; bool valid; _readonly = pParams.inList("readOnly"); _new->hide(); _delete->hide(); param = pParams.value("taxzone_id", &valid); if (valid) _taxzoneId = param.toInt(); param = pParams.value("taxtype_id", &valid); if (valid) _taxType->setId(param.toInt()); else clear(); param = pParams.value("date", &valid); if (valid) _subtotal->setEffective(param.toDate()); param = pParams.value("subtotal", &valid); if (valid) _subtotal->setLocalValue(param.toDouble()); param = pParams.value("curr_id", &valid); if (valid) _subtotal->setId(param.toInt()); param = pParams.value("order_id", &valid); if (valid) _orderid = param.toInt(); param = pParams.value("order_type", &valid); if (valid) _ordertype = param.toString(); param = pParams.value("display_type", &valid); if (valid) _displayType = param.toString(); _adjustment = pParams.inList("adjustment"); param = pParams.value("sense", &valid); if (valid) _sense = param.toInt(); if (_readonly) { _taxType->setEnabled(FALSE); _cancel->setText(tr("&Close")); } if(_adjustment && !_readonly) { _taxType->setEnabled(FALSE); _new->show(); _delete->show(); } sPopulate(); return NoError; }
// return in meter double MapPage::evalGetDistanceInMeter() const { QVariant distance = this->mainFrame()->evaluateJavaScript("curRoute.getDistance();"); return distance.toDouble(); }
QVariant QSystemLocale::query(QueryType type, QVariant in) const { QSystemLocaleData *d = qSystemLocaleData(); if (type == LocaleChanged) { d->readEnvironment(); return QVariant(); } QReadLocker locker(&d->lock); 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 StandaloneMonthNameLong: return lc_time.standaloneMonthName(in.toInt(), QLocale::LongFormat); case StandaloneMonthNameShort: return lc_time.standaloneMonthName(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; return QVariant((int)QLocale(meas_locale).measurementSystem()); } case UILanguages: { if (!d->uiLanguages.isEmpty()) return d->uiLanguages; QString languages = QString::fromLatin1(qgetenv("LANGUAGE")); QStringList lst; if (languages.isEmpty()) lst.append(QString::fromLatin1(d->lc_messages_var)); else lst = languages.split(QLatin1Char(':')); for (int i = 0; i < lst.size(); ++i) { const QString &name = lst.at(i); QString lang, script, cntry; if (qt_splitLocaleName(name, lang, script, cntry)) { if (!cntry.length()) d->uiLanguages.append(lang); else d->uiLanguages.append(lang % QLatin1Char('-') % cntry); } } return d->uiLanguages.isEmpty() ? QVariant() : QVariant(d->uiLanguages); } 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: Q_ASSERT(false); default: break; } return QVariant(); }
void QgsLabelPropertyDialog::setDataDefinedValues( const QgsPalLayerSettings &layerSettings, QgsVectorLayer* vlayer ) { //loop through data defined properties and set all the GUI widget values. We can do this //even if the data defined property is set to an expression, as it's useful to show //users what the evaluated property is... QgsExpressionContext context; context << QgsExpressionContextUtils::globalScope() << QgsExpressionContextUtils::projectScope() << QgsExpressionContextUtils::atlasScope( nullptr ) << QgsExpressionContextUtils::mapSettingsScope( QgisApp::instance()->mapCanvas()->mapSettings() ) << QgsExpressionContextUtils::layerScope( vlayer ); context.setFeature( mCurLabelFeat ); QMap< QgsPalLayerSettings::DataDefinedProperties, QgsDataDefined* >::const_iterator propIt = mDataDefinedProperties.constBegin(); for ( ; propIt != mDataDefinedProperties.constEnd(); ++propIt ) { QgsDataDefined* dd = propIt.value(); if ( !dd || !dd->isActive() ) { continue; } if ( !dd->expressionIsPrepared() ) { dd->prepareExpression( context ); } //TODO - pass expression context QVariant result = layerSettings.dataDefinedValue( propIt.key(), mCurLabelFeat, vlayer->fields(), &context ); if ( !result.isValid() || result.isNull() ) { //could not evaluate data defined value continue; } bool ok = false; switch ( propIt.key() ) { case QgsPalLayerSettings::Show: { int showLabel = result.toInt( &ok ); mShowLabelChkbx->setChecked( !ok || showLabel != 0 ); break; } case QgsPalLayerSettings::AlwaysShow: mAlwaysShowChkbx->setChecked( result.toBool() ); break; case QgsPalLayerSettings::MinScale: { int minScale = result.toInt( &ok ); if ( ok ) { mMinScaleSpinBox->setValue( minScale ); } break; } case QgsPalLayerSettings::MaxScale: { int maxScale = result.toInt( &ok ); if ( ok ) { mMaxScaleSpinBox->setValue( maxScale ); } break; } case QgsPalLayerSettings::BufferSize: { double bufferSize = result.toDouble( &ok ); if ( ok ) { mBufferSizeSpinBox->setValue( bufferSize ); } break; } case QgsPalLayerSettings::PositionX: { double posX = result.toDouble( &ok ); if ( ok ) { mXCoordSpinBox->setValue( posX ); } break; } case QgsPalLayerSettings::PositionY: { double posY = result.toDouble( &ok ); if ( ok ) { mYCoordSpinBox->setValue( posY ); } break; } case QgsPalLayerSettings::LabelDistance: { double labelDist = result.toDouble( &ok ); if ( ok ) { mLabelDistanceSpinBox->setValue( labelDist ); } break; } case QgsPalLayerSettings::Hali: mHaliComboBox->setCurrentIndex( mHaliComboBox->findData( result.toString() ) ); break; case QgsPalLayerSettings::Vali: mValiComboBox->setCurrentIndex( mValiComboBox->findData( result.toString() ) ); break; case QgsPalLayerSettings::BufferColor: mBufferColorButton->setColor( QColor( result.toString() ) ); break; case QgsPalLayerSettings::Color: mFontColorButton->setColor( QColor( result.toString() ) ); break; case QgsPalLayerSettings::Rotation: { double rot = result.toDouble( &ok ); if ( ok ) { mRotationSpinBox->setValue( rot ); } break; } case QgsPalLayerSettings::Size: { double size = result.toDouble( &ok ); if ( ok ) { mFontSizeSpinBox->setValue( size ); } else { mFontSizeSpinBox->setValue( 0 ); } break; } default: break; } } }
bool DomConvenience::variantToElement(const QVariant& v, QDomElement& e) { bool ok = true; clearAttributes(e); switch (v.type()) { case QVariant::String: e.setTagName("string"); e.setAttribute("value", v.toString().utf8()); break; case QVariant::CString: e.setTagName("string"); e.setAttribute("value", v.toCString()); break; case QVariant::Int: e.setTagName("int"); e.setAttribute("value", v.toInt()); break; case QVariant::UInt: e.setTagName("uint"); e.setAttribute("value", v.toUInt()); break; case QVariant::Double: e.setTagName("double"); e.setAttribute("value", v.toDouble()); break; case QVariant::Bool: e.setTagName("bool"); e.setAttribute("value", boolString(v.toBool())); break; case QVariant::Color: { e.setTagName("color"); QColor color = v.toColor(); e.setAttribute("red", color.red()); e.setAttribute("green", color.green()); e.setAttribute("blue", color.blue()); } break; case QVariant::Pen: { e.setTagName("pen"); QPen pen = v.toPen(); e.setAttribute("red", pen.color().red()); e.setAttribute("green", pen.color().green()); e.setAttribute("blue", pen.color().blue()); e.setAttribute("style", pen.style()); e.setAttribute("cap", pen.capStyle()); e.setAttribute("join", pen.joinStyle()); } break; case QVariant::Brush: { e.setTagName("brush"); QBrush brush = v.toBrush(); e.setAttribute("red", brush.color().red()); e.setAttribute("green", brush.color().green()); e.setAttribute("blue", brush.color().blue()); e.setAttribute("style", brush.style()); } break; case QVariant::Point: { e.setTagName("point"); QPoint point = v.toPoint(); e.setAttribute("x", point.x()); e.setAttribute("y", point.y()); } break; case QVariant::Rect: { e.setTagName("rect"); QRect rect = v.toRect(); e.setAttribute("x", rect.x()); e.setAttribute("y", rect.y()); e.setAttribute("width", rect.width()); e.setAttribute("height", rect.height()); } break; case QVariant::Size: { e.setTagName("size"); QSize qsize = v.toSize(); e.setAttribute("width", qsize.width()); e.setAttribute("height", qsize.height()); } break; case QVariant::Font: { e.setTagName("font"); QFont f(v.toFont()); e.setAttribute("family", f.family()); e.setAttribute("pointsize", f.pointSize()); e.setAttribute("bold", boolString(f.bold())); e.setAttribute("italic", boolString(f.italic())); e.setAttribute("underline", boolString(f.underline())); e.setAttribute("strikeout", boolString(f.strikeOut())); } break; case QVariant::SizePolicy: { e.setTagName("sizepolicy"); QSizePolicy sp(v.toSizePolicy()); e.setAttribute("hsizetype", sp.horData()); e.setAttribute("vsizetype", sp.verData()); e.setAttribute("horstretch", sp.horStretch()); e.setAttribute("verstretch", sp.verStretch()); } break; case QVariant::Cursor: e.setTagName("cursor"); e.setAttribute("shape", v.toCursor().shape()); break; case QVariant::StringList: { e.setTagName("stringlist"); uint j; QDomNode n; QDomNodeList stringNodeList = e.elementsByTagName("string"); QDomElement stringElem; QStringList stringList = v.toStringList(); QStringList::Iterator it = stringList.begin(); for (j = 0; ((j < stringNodeList.length()) && (it != stringList.end())); j++) { // get the current string element stringElem = stringNodeList.item(j).toElement(); // set it to the current string variantToElement(QVariant(*it), stringElem); // iterate to the next string ++it; } // more nodes in previous stringlist then current, remove excess nodes if (stringNodeList.count() > stringList.count()) { while (j < stringNodeList.count()) e.removeChild(stringNodeList.item(j).toElement()); } else if (j <stringList.count()) { while (it != stringList.end()) { // create a new element stringElem = m_doc.createElement("string"); // set it to the currentstring variantToElement(QVariant(*it), stringElem); // append it to the current element e.appendChild(stringElem); // iterate to the next string ++it; } } } break; case QVariant::KeySequence: e.setTagName("key"); e.setAttribute("sequence", (QString)v.toKeySequence()); break; case QVariant::ByteArray: // this is only for [u]int64_t { e.setTagName("uint64"); QByteArray ba = v.toByteArray(); // make sure this only handles [u]int64_t's if (ba.size() != sizeof(uint64_t)) { qWarning("Don't know how to persist variant of type: %s (%d) (size=%d)!", v.typeName(), v.type(), ba.size()); ok = false; break; } // convert the data back into a uint64_t uint64_t num = *(uint64_t*)ba.data(); QChar buff[33]; QChar* p = &buff[32]; const char* digitSet = "0123456789abcdef"; int len = 0; // construct the string do { *--p = digitSet[((int)(num%16))]; num = num >> 4; // divide by 16 len++; } while ( num ); // store it in a QString QString storage; storage.setUnicode(p, len); // set the value e.setAttribute("value", storage); } break; #if 0 case QVariant::List: case QVaraint::Map: #endif default: qWarning("Don't know how to persist variant of type: %s (%d)!", v.typeName(), v.type()); ok = false; break; } return ok; }
bool ST_elements_model::setData(const QModelIndex &index, const QVariant &value, int role) { ST_element &aRow(myStage().rows[index.row()]); if (index.isValid() && role == Qt::EditRole) { switch(index.column()) { case 0: aRow.isEnabled = value.toBool(); break; case 1: aRow.xyz[0] = value.toDouble(); break; case 2: aRow.xyz[1] = value.toDouble(); break; case 3: aRow.xyz[2] = value.toDouble(); break; case 4: aRow.aim[0] = value.toDouble(); break; case 5: aRow.aim[1] = value.toDouble(); break; case 6: aRow.aim[2] = value.toDouble(); break; case 7: aRow.zrot = value.toDouble(); break; case 8: try { aRow.aperture.myType = ST_aperture::stringToType(value.toString()); break; } catch (std::invalid_argument& e) { qDebug() << e.what(); return false; } case 9: aRow.aperture.data[0] = value.toDouble(); break; case 10: aRow.aperture.data[1] = value.toDouble(); break; case 11: aRow.aperture.data[2] = value.toDouble(); break; case 12: aRow.aperture.data[3] = value.toDouble(); break; case 13: aRow.aperture.data[4] = value.toDouble(); break; case 14: aRow.aperture.data[5] = value.toDouble(); break; case 15: aRow.aperture.data[6] = value.toDouble(); break; case 16: aRow.aperture.data[7] = value.toDouble(); break; case 17: try { aRow.surface->type = ST_surface::stringToType(value.toString()); break; } catch (std::invalid_argument& e) { qDebug() << e.what(); return false; } case 18: aRow.surface->data[0] = value.toDouble(); break; case 19: aRow.surface->data[1] = value.toDouble(); break; case 20: aRow.surface->data[2] = value.toDouble(); break; case 21: aRow.surface->data[3] = value.toDouble(); break; case 22: aRow.surface->data[4] = value.toDouble(); break; case 23: aRow.surface->data[5] = value.toDouble(); break; case 24: aRow.surface->data[6] = value.toDouble(); break; case 25: aRow.surface->data[7] = value.toDouble(); break; case 26: aRow.surface->filename = value.toString(); break; case 27: try { aRow.myIntent = ST_element::stringToType(value.toString()); break; } catch (std::invalid_argument& e) { qDebug() << e.what(); return false; } case 28: aRow.myName = value.toString(); break; default: return false; } emit(dataChanged(index, index)); } return false; }
bool MatrixModel::muParserCalculate(int startRow, int endRow, int startCol, int endCol) { ScriptingEnv *scriptEnv = d_matrix->scriptingEnv(); muParserScript *mup = new muParserScript(scriptEnv, QString("<%1>").arg(d_matrix->objectName()), d_matrix); connect(mup, SIGNAL(error(const QString&,const QString&,int)), scriptEnv, SIGNAL(error(const QString&,const QString&,int))); connect(mup, SIGNAL(print(const QString&)), scriptEnv, SIGNAL(print(const QString&))); if (endRow < 0) endRow = d_rows - 1; if (endCol < 0) endCol = d_cols - 1; if (endCol >= d_cols) setColumnCount(endCol + 1); if (endRow >= d_rows) setRowCount(endRow + 1); double dx = d_matrix->dx(); double dy = d_matrix->dy(); double *ri = mup->defineVariable("i"); double *rr = mup->defineVariable("row"); double *cj = mup->defineVariable("j"); double *cc = mup->defineVariable("col"); double *x = mup->defineVariable("x"); double *y = mup->defineVariable("y"); if (!mup->compile( d_matrix->formula())){ QApplication::restoreOverrideCursor(); return false; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); double x_start = d_matrix->xStart(); double y_start = d_matrix->yStart(); if (mup->codeLines() == 1){ for(int row = startRow; row <= endRow; row++){ double r = row + 1.0; *ri = r; *rr = r; *y = y_start + row*dy; int aux = row*d_cols + startCol; for(int col = startCol; col <= endCol; col++){ double c = col + 1.0; *cj = c; *cc = c; *x = x_start + col*dx; d_data[aux++] = mup->evalSingleLine(); } } } else { QVariant res; for(int row = startRow; row <= endRow; row++){ double r = row + 1.0; *ri = r; *rr = r; *y = y_start + row*dy; int aux = row*d_cols + startCol; for(int col = startCol; col <= endCol; col++){ double c = col + 1.0; *cj = c; *cc = c; *x = x_start + col*dx; res = mup->evaluate(d_matrix->formula()); if (res.canConvert(QVariant::Double)) d_data[aux++] = res.toDouble(); else d_data[aux++] = GSL_NAN; qApp->processEvents(); } } } QApplication::restoreOverrideCursor(); return true; }
QDomElement MaiaObject::toXml(QVariant arg) { //dummy document QDomDocument doc; //value element, we need this in each case QDomElement tagValue = doc.createElement("value"); switch(arg.type()) { case QVariant::String: { QDomElement tagString = doc.createElement("string"); QDomText textString = doc.createTextNode(arg.toString()); tagValue.appendChild(tagString); tagString.appendChild(textString); return tagString; } case QVariant::Int: { QDomElement tagInt = doc.createElement("int"); QDomText textInt = doc.createTextNode(QString::number(arg.toInt())); tagValue.appendChild(tagInt); tagInt.appendChild(textInt); return tagValue; } case QVariant::Double: { QDomElement tagDouble = doc.createElement("double"); QDomText textDouble = doc.createTextNode(QString::number(arg.toDouble())); tagValue.appendChild(tagDouble); tagDouble.appendChild(textDouble); return tagValue; } case QVariant::Bool: { QString textValue = arg.toBool() ? "1" : "0"; QDomElement tag = doc.createElement("boolean"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::ByteArray: { QString textValue = arg.toByteArray().toBase64(); QDomElement tag = doc.createElement("base64"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::DateTime: { QString textValue = arg.toDateTime().toString("yyyyMMddThh:mm:ss"); QDomElement tag = doc.createElement("datetime.iso8601"); QDomText text = doc.createTextNode(textValue); tagValue.appendChild(tag); tag.appendChild(text); return tagValue; } case QVariant::List: { QDomElement tagArray = doc.createElement("array"); QDomElement tagData = doc.createElement("data"); tagArray.appendChild(tagData); tagValue.appendChild(tagArray); const QList<QVariant> args = arg.toList(); for(int i = 0; i < args.size(); ++i) { tagData.appendChild(toXml(args.at(i))); } return tagValue; } case QVariant::Map: { QDomElement tagStruct = doc.createElement("struct"); QDomElement member; QDomElement name; tagValue.appendChild(tagStruct); QMap<QString, QVariant> map = arg.toMap(); QMapIterator<QString, QVariant> i(map); while(i.hasNext()) { i.next(); member = doc.createElement("member"); name = doc.createElement("name"); // (key) -> name -> member -> struct tagStruct.appendChild(member); member.appendChild(name); name.appendChild(doc.createTextNode(i.key())); // add variables by recursion member.appendChild(toXml(i.value())); } return tagValue; } default: qDebug() << "Failed to marshal unknown variant type: " << arg.type() << endl; } return QDomElement(); //QString::null; }
bool SqlitePreparedStatement::bindValue(KDbField *field, const QVariant& value, int par) { if (value.isNull()) { //no value to bind or the value is null: bind NULL int res = sqlite3_bind_null(m_sqlResult->prepared_st, par); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } return true; } if (field->isTextType()) { //! @todo optimize: make a static copy so SQLITE_STATIC can be used const QByteArray utf8String(value.toString().toUtf8()); int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, utf8String.constData(), utf8String.length(), SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } return true; } switch (field->type()) { case KDbField::Byte: case KDbField::ShortInteger: case KDbField::Integer: { //! @todo what about unsigned > INT_MAX ? bool ok; const int intValue = value.toInt(&ok); if (ok) { int res = sqlite3_bind_int(m_sqlResult->prepared_st, par, intValue); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } } else { int res = sqlite3_bind_null(m_sqlResult->prepared_st, par); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } } break; } case KDbField::Float: case KDbField::Double: { int res = sqlite3_bind_double(m_sqlResult->prepared_st, par, value.toDouble()); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } case KDbField::BigInteger: { //! @todo what about unsigned > LLONG_MAX ? bool ok; const qint64 int64Value = value.toLongLong(&ok); if (ok) { int res = sqlite3_bind_int64(m_sqlResult->prepared_st, par, int64Value); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } } else { int res = sqlite3_bind_null(m_sqlResult->prepared_st, par); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } } break; } case KDbField::Boolean: { int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, value.toBool() ? "1" : "0", 1, SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } case KDbField::Time: { int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, qPrintable(value.toTime().toString(Qt::ISODate)), QLatin1String("HH:MM:SS").size(), SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } case KDbField::Date: { int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, qPrintable(value.toDate().toString(Qt::ISODate)), QLatin1String("YYYY-MM-DD").size(), SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } case KDbField::DateTime: { int res = sqlite3_bind_text(m_sqlResult->prepared_st, par, qPrintable(value.toDateTime().toString(Qt::ISODate)), QLatin1String("YYYY-MM-DDTHH:MM:SS").size(), SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } case KDbField::BLOB: { const QByteArray byteArray(value.toByteArray()); int res = sqlite3_bind_blob(m_sqlResult->prepared_st, par, byteArray.constData(), byteArray.size(), SQLITE_TRANSIENT /*??*/); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } break; } default: { sqliteWarning() << "unsupported field type:" << field->type() << "- NULL value bound to column #" << par; int res = sqlite3_bind_null(m_sqlResult->prepared_st, par); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(&m_result); return false; } } } //switch return true; }
void PoitemTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *pModel, const QModelIndex &index) const { if (DEBUG) qDebug("PoitemTableDelegate::setModelData() entered"); bool hitError = false; QVariant oldval = pModel->data(index); PoitemTableModel *model = static_cast<PoitemTableModel*>(pModel); switch (index.column()) { case ITEM_NUMBER_COL: { ItemLineEdit *item = static_cast<ItemLineEdit*>(editor); if (item->itemNumber() != oldval.toString()) { if (item->itemNumber().isEmpty()) { model->setData(index, new QVariant()); model->setData(model->index(index.row(), ITEM_ID_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), new QVariant()); model->setData(model->index(index.row(), WAREHOUS_ID_COL), new QVariant()); model->setData(model->index(index.row(), WAREHOUS_CODE_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_ITEMSRC_ID_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_VEND_ITEM_NUMBER_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_VEND_ITEM_DESCRIP_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_VEND_UOM_COL), new QVariant()); model->setData(model->index(index.row(), ITEMSRC_MINORDQTY_COL), new QVariant()); model->setData(model->index(index.row(), ITEMSRC_MULTORDQTY_COL), new QVariant()); model->setData(model->index(index.row(), ITEMSRC_INVVENDORUOMRATIO_COL), new QVariant()); model->setData(model->index(index.row(), POITEM_INVVENDUOMRATIO_COL), new QVariant()); model->setData(model->index(index.row(), EARLIESTDATE_COL), new QVariant()); } else { model->setData(index, item->itemNumber()); model->setData(model->index(index.row(), ITEM_ID_COL), item->id()); if (item->isValid()) { XSqlQuery itemq; itemq.prepare("SELECT (warehous_id=:preferred) AS preferred, " " itemsite_id, warehous_id, warehous_code " "FROM itemsite, whsinfo " "WHERE ((itemsite_item_id=:item_id)" " AND (itemsite_warehous_id=warehous_id)) " "ORDER BY preferred DESC, warehous_code " "LIMIT 1;"); itemq.bindValue(":item_id", item->id()); itemq.bindValue(":preferred", _x_preferences->value("PreferredWarehouse").toInt()); itemq.exec(); if (itemq.first()) { model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), itemq.value("itemsite_id").toInt()); model->setData(model->index(index.row(), WAREHOUS_ID_COL), itemq.value("warehous_id").toInt()); model->setData(model->index(index.row(), WAREHOUS_CODE_COL), itemq.value("warehous_code").toString()); } else if (itemq.lastError().type() != QSqlError::None) { systemError(0, itemq.lastError().databaseText(), __FILE__, __LINE__); hitError = true; break; } else { systemError(0, QString("Could not find Item Site for %1 (%2).") .arg(item->itemNumber()).arg(item->id())); hitError = true; break; } if (_metrics->boolean("RequireStdCostForPOItem")) { XSqlQuery stdcostq; stdcostq.prepare("SELECT stdCost(:item_id) AS result"); stdcostq.bindValue(":item_id", item->id()); stdcostq.exec(); if(stdcostq.first() && stdcostq.value("result").toDouble() == 0.0) { QMessageBox::critical(0, tr("Selected Item Missing Cost"), tr("<p>The selected item has no Std. Costing information. " "Please see your controller to correct this situation " "before continuing.")); model->setData(index, new QString()); model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), new QVariant()); model->setData(model->index(index.row(), WAREHOUS_ID_COL), new QVariant()); model->setData(model->index(index.row(), WAREHOUS_CODE_COL), new QString()); model->setData(index, new QString()); hitError = true; break; } else if (stdcostq.lastError().type() != QSqlError::None) { systemError(0, stdcostq.lastError().databaseText(), __FILE__, __LINE__); hitError = true; break; } } XSqlQuery itemsrcq; itemsrcq.prepare( "SELECT itemsrc_id, itemsrc_vend_item_number," " itemsrc_vend_item_descrip, itemsrc_vend_uom," " itemsrc_minordqty," " itemsrc_multordqty," " itemsrc_invvendoruomratio," " (CURRENT_DATE + itemsrc_leadtime) AS earliestdate " "FROM pohead, itemsrc " "WHERE ( (itemsrc_vend_id=pohead_vend_id)" " AND (itemsrc_item_id=:item_id)" " AND (pohead_id=:pohead_id) );" ); itemsrcq.bindValue(":item_id", item->id()); itemsrcq.bindValue(":pohead_id", model->headId()); itemsrcq.exec(); if (itemsrcq.first()) { model->setData(model->index(index.row(), POITEM_ITEMSRC_ID_COL), itemsrcq.value("itemsrc_id").toInt()); model->setData(model->index(index.row(), POITEM_VEND_ITEM_NUMBER_COL), itemsrcq.value("itemsrc_vend_item_number").toString()); model->setData(model->index(index.row(), POITEM_VEND_ITEM_DESCRIP_COL), itemsrcq.value("itemsrc_vend_item_descrip").toString()); model->setData(model->index(index.row(), POITEM_VEND_UOM_COL), itemsrcq.value("itemsrc_vend_uom").toString()); model->setData(model->index(index.row(), ITEMSRC_MINORDQTY_COL), itemsrcq.value("itemsrc_minordqty").toDouble()); model->setData(model->index(index.row(), ITEMSRC_MULTORDQTY_COL), itemsrcq.value("itemsrc_multordqty").toDouble()); model->setData(model->index(index.row(), ITEMSRC_INVVENDORUOMRATIO_COL), itemsrcq.value("itemsrc_invvendoruomratio").toDouble()); model->setData(model->index(index.row(), POITEM_INVVENDUOMRATIO_COL), itemsrcq.value("itemsrc_invvendoruomratio").toDouble()); model->setData(model->index(index.row(), EARLIESTDATE_COL), itemsrcq.value("earliestdate").toDate()); if (_metrics->boolean("UseEarliestAvailDateOnPOItem")) model->setData(model->index(index.row(), POITEM_DUEDATE_COL), itemsrcq.value("earliestdate").toDate()); } else if (itemsrcq.lastError().type() != QSqlError::None) { systemError(0, itemsrcq.lastError().databaseText(), __FILE__, __LINE__); hitError = true; break; } } } } break; } case WAREHOUS_CODE_COL: { WComboBox *whs = static_cast<WComboBox*>(editor); if (whs->id() < 0) { model->setData(model->index(index.row(), WAREHOUS_ID_COL), QVariant()); model->setData(index, QVariant()); } else if (whs->id() != oldval.toInt()) { model->setData(model->index(index.row(), WAREHOUS_ID_COL), whs->id()); model->setData(index, whs->currentText()); if (whs->isValid()) { XSqlQuery itemq; itemq.prepare("SELECT itemsite_id " "FROM itemsite " "WHERE ((itemsite_item_id=:item_id)" " AND (itemsite_warehous_id=:whs_id)) " "LIMIT 1;"); itemq.bindValue(":item_id", model->index(index.row(), ITEM_ID_COL).data()); itemq.bindValue(":whs_id", whs->id()); itemq.exec(); if (itemq.first()) { model->setData(model->index(index.row(), POITEM_ITEMSITE_ID_COL), itemq.value("itemsite_id").toInt()); } else if (itemq.lastError().type() != QSqlError::None) { systemError(0, itemq.lastError().databaseText(), __FILE__, __LINE__); hitError = true; break; } else { systemError(0, QString("Could not find Item Site for %1 in %2.") .arg(model->index(index.row(), ITEM_NUMBER_COL).data().toString()) .arg(whs->currentText())); hitError = true; break; } } } break; } case POITEM_VEND_ITEM_NUMBER_COL: { XLineEdit *lineedit = static_cast<XLineEdit*>(editor); if (lineedit->text() != oldval.toString()) model->setData(index, lineedit->text()); break; } case POITEM_FREIGHT_COL: { XLineEdit *lineedit = static_cast<XLineEdit*>(editor); if (lineedit->toDouble() != oldval.toDouble()) model->setData(index, lineedit->toDouble()); break; } case POITEM_QTY_ORDERED_COL: { XLineEdit *lineedit = static_cast<XLineEdit*>(editor); if (lineedit->text().isEmpty()) { model->setData(index, QVariant()); model->setData(model->index(index.row(), EXTPRICE_COL), QVariant()); break; } double qty = lineedit->toDouble(); if (qty != oldval.toDouble()) { model->setData(index, qty); if (model->data(model->index(index.row(), POITEM_QTY_ORDERED_COL)).toDouble() > 0 && model->data(model->index(index.row(), POITEM_ITEMSRC_ID_COL)).toInt() > 0) { q.prepare( "SELECT ROUND(currToCurr(itemsrcp_curr_id, :curr_id, itemsrcp_price, :effective), :prec) " "AS new_itemsrcp_price " "FROM itemsrcp " "WHERE ( (itemsrcp_itemsrc_id=:itemsrc_id)" " AND (itemsrcp_qtybreak <= :qty) ) " "ORDER BY itemsrcp_qtybreak DESC " "LIMIT 1;" ); q.bindValue(":itemsrc_id", model->data(model->index(index.row(), POITEM_ITEMSRC_ID_COL)).toInt()); q.bindValue(":qty", model->data(model->index(index.row(), POITEM_QTY_ORDERED_COL)).toDouble()); q.bindValue(":curr_id", model->currId()); q.bindValue(":effective", model->transDate().toString()); q.bindValue(":prec", omfgThis->priceVal()->decimals()); q.exec(); if (q.first()) { model->setData(model->index(index.row(), POITEM_UNITPRICE_COL), q.value("new_itemsrcp_price").toDouble()); } else if (q.lastError().type() != QSqlError::None) { systemError(0, q.lastError().databaseText(), __FILE__, __LINE__); hitError = true; break; } else model->setData(model->index(index.row(), POITEM_UNITPRICE_COL), 0); } double prc = model->data(model->index(index.row(), POITEM_UNITPRICE_COL)).toDouble(); model->setData(model->index(index.row(), EXTPRICE_COL), (qty * prc)); } break; } case POITEM_UNITPRICE_COL: { XLineEdit *lineedit = static_cast<XLineEdit*>(editor); if (lineedit->text().isEmpty()) { model->setData(index, QVariant()); model->setData(model->index(index.row(), EXTPRICE_COL), QVariant()); break; } double prc = lineedit->text().toDouble(); if (prc != oldval.toDouble()) { model->setData(index, prc); double qty = model->data(model->index(index.row(),POITEM_QTY_ORDERED_COL)).toDouble(); model->setData(model->index(index.row(), EXTPRICE_COL), (qty * prc)); } break; } case POITEM_DUEDATE_COL: { XDateEdit *duedate = static_cast<XDateEdit*>(editor); duedate->parseDate(); if (duedate->date() != oldval.toDate()) { if (DEBUG) qDebug("PoitemTableDelegate::setModelData() setting duedate to %s with null %d, valid %d", qPrintable(duedate->date().toString()), duedate->isNull(), duedate->isValid()); model->setData(index, duedate->date()); } break; } #ifdef QE_NONINVENTORY case EXPCAT_CODE_COL: { ExpenseLineEdit *exp = static_cast<ExpenseLineEdit*>(editor); if (exp->id() != oldval.toInt()) { model->setData(model->index(index.row(), POITEM_EXPCAT_ID_COL), exp->id()); model->setData(index, exp->text()); } break; } #endif default: break; } QTableView *view = qobject_cast<QTableView*>(parent()); if (view) { if (hitError) view->setCurrentIndex(index); else if (index.row() >= (model->rowCount() - 1)) { QHeaderView* header = view->horizontalHeader(); if (header->visualIndex(index.column()) >= (header->count() - header->hiddenSectionCount() - 1)) { model->insertRow(model->rowCount()); } } } return; }
/** * @brief FlightDataModel::setData Set the data at a given location * @param index Specifies both the row (waypoint) and column (field0 * @param value The new value * @param role Used by the Qt MVC to determine what to do. Should be Qt::EditRole * @return True if setting data succeeded, otherwise false */ bool FlightDataModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { pathPlanData *row = dataStorage.at(index.row()); // Do not allow changing any values except locked when the column is locked if (row->locked && index.column() != (int) FlightDataModel::LOCKED) return false; struct FlightDataModel::NED NED; QModelIndex otherIndex; switch(index.column()) { case WPDESCRITPTION: row->wpDescritption=value.toString(); break; case LATPOSITION: row->latPosition=value.toDouble(); // Indicate this also changed the north otherIndex = this->index(index.row(), FlightDataModel::NED_NORTH); emit dataChanged(otherIndex,otherIndex); break; case LNGPOSITION: row->lngPosition=value.toDouble(); // Indicate this also changed the east otherIndex = this->index(index.row(), FlightDataModel::NED_EAST); emit dataChanged(otherIndex,otherIndex); break; case ALTITUDE: row->altitude=value.toDouble(); // Indicate this also changed the NED down otherIndex = this->index(index.row(), FlightDataModel::NED_DOWN); emit dataChanged(otherIndex,otherIndex); break; case NED_NORTH: NED = getNED(index.row()); NED.North = value.toDouble(); setNED(index.row(), NED); // Indicate this also changed the latitude otherIndex = this->index(index.row(), FlightDataModel::LATPOSITION); emit dataChanged(otherIndex,otherIndex); break; case NED_EAST: NED = getNED(index.row()); NED.East = value.toDouble(); setNED(index.row(), NED); // Indicate this also changed the longitude otherIndex = this->index(index.row(), FlightDataModel::LNGPOSITION); emit dataChanged(otherIndex,otherIndex); break; case NED_DOWN: NED = getNED(index.row()); NED.Down = value.toDouble(); setNED(index.row(), NED); // Indicate this also changed the altitude otherIndex = this->index(index.row(), FlightDataModel::ALTITUDE); emit dataChanged(otherIndex,otherIndex); break; case VELOCITY: row->velocity=value.toFloat(); break; case MODE: row->mode=value.toInt(); break; case MODE_PARAMS: row->mode_params=value.toFloat(); break; case LOCKED: row->locked = value.toBool(); break; default: return false; } emit dataChanged(index,index); return true; } return false; }
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 } }
void KisUnsharpFilter::process(KisPaintDeviceSP device, const QRect& applyRect, const KisFilterConfiguration* config, KoUpdater* progressUpdater ) const { QPointer<KoUpdater> filterUpdater = 0; QPointer<KoUpdater> convolutionUpdater = 0; KoProgressUpdater* updater = 0; if (progressUpdater) { updater = new KoProgressUpdater(progressUpdater); updater->start(); // Two sub-sub tasks that each go from 0 to 100. convolutionUpdater = updater->startSubtask(); filterUpdater = updater->startSubtask(); } if (!config) config = new KisFilterConfiguration(id().id(), 1); QVariant value; uint halfSize = (config->getProperty("halfSize", value)) ? value.toUInt() : 5; uint brushsize = 2 * halfSize + 1; double amount = (config->getProperty("amount", value)) ? value.toDouble() : 0.5; uint threshold = (config->getProperty("threshold", value)) ? value.toUInt() : 10; KisCircleMaskGenerator* kas = new KisCircleMaskGenerator(brushsize, 1, halfSize, halfSize, 2); KisConvolutionKernelSP kernel = KisConvolutionKernel::fromMaskGenerator(kas); KisPaintDeviceSP interm = new KisPaintDevice(*device); const KoColorSpace * cs = interm->colorSpace(); KoConvolutionOp * convolutionOp = cs->convolutionOp(); KisConvolutionPainter painter(interm); // TODO no need for a full copy and then a transaction if (progressUpdater) { painter.setProgress(convolutionUpdater); } QBitArray channelFlags = config->channelFlags(); if (channelFlags.isEmpty()) { channelFlags = cs->channelFlags(); } painter.setChannelFlags(channelFlags); painter.beginTransaction("convolution step"); painter.applyMatrix(kernel, interm, applyRect.topLeft(), applyRect.topLeft(), applyRect.size(), BORDER_REPEAT); painter.deleteTransaction(); if (progressUpdater && progressUpdater->interrupted()) { return; } KisHLineIteratorSP dstIt = device->createHLineIteratorNG(applyRect.x(), applyRect.y(), applyRect.width()); KisHLineConstIteratorSP intermIt = interm->createHLineConstIteratorNG(applyRect.x(), applyRect.y(), applyRect.width()); int cdepth = cs -> pixelSize(); quint8 *colors[2]; colors[0] = new quint8[cdepth]; colors[1] = new quint8[cdepth]; int pixelsProcessed = 0; qreal weights[2]; qreal factor = 128; // XXX: Added static cast to avoid warning weights[0] = static_cast<qreal>(factor * (1. + amount)); weights[1] = static_cast<qreal>(-factor * amount); int steps = 100 / applyRect.width() * applyRect.height(); for (int j = 0; j < applyRect.height(); j++) { do { quint8 diff = cs->difference(dstIt->oldRawData(), intermIt->oldRawData()); if (diff > threshold) { memcpy(colors[0], dstIt->oldRawData(), cdepth); memcpy(colors[1], intermIt->oldRawData(), cdepth); convolutionOp->convolveColors(colors, weights, dstIt->rawData(), factor, 0, 2.0, channelFlags); } else { memcpy(dstIt->rawData(), dstIt->oldRawData(), cdepth); } ++pixelsProcessed; if (progressUpdater) filterUpdater->setProgress(steps * pixelsProcessed); intermIt->nextPixel(); } while (dstIt->nextPixel()); if (progressUpdater && progressUpdater->interrupted()) { return; } dstIt->nextRow(); intermIt->nextRow(); } delete colors[0]; delete colors[1]; delete updater; if (progressUpdater) progressUpdater->setProgress(100); }
void SketcherValidation::on_findButton_clicked() { std::vector<VertexIds> vertexIds; const std::vector<Part::Geometry *>& geom = sketch->getInternalGeometry(); for (std::size_t i=0; i<geom.size(); i++) { Part::Geometry* g = geom[i]; if (g->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *segm = static_cast<const Part::GeomLineSegment*>(g); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::start; id.v = segm->getStartPoint(); vertexIds.push_back(id); id.GeoId = (int)i; id.PosId = Sketcher::end; id.v = segm->getEndPoint(); vertexIds.push_back(id); } else if (g->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *segm = static_cast<const Part::GeomArcOfCircle*>(g); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::start; id.v = segm->getStartPoint(/*emulateCCW=*/true); vertexIds.push_back(id); id.GeoId = (int)i; id.PosId = Sketcher::end; id.v = segm->getEndPoint(/*emulateCCW=*/true); vertexIds.push_back(id); } else if (g->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *segm = static_cast<const Part::GeomArcOfEllipse*>(g); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::start; id.v = segm->getStartPoint(/*emulateCCW=*/true); vertexIds.push_back(id); id.GeoId = (int)i; id.PosId = Sketcher::end; id.v = segm->getEndPoint(/*emulateCCW=*/true); vertexIds.push_back(id); } else if (g->getTypeId() == Part::GeomArcOfHyperbola::getClassTypeId()) { const Part::GeomArcOfHyperbola *segm = static_cast<const Part::GeomArcOfHyperbola*>(g); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::start; id.v = segm->getStartPoint(); vertexIds.push_back(id); id.GeoId = (int)i; id.PosId = Sketcher::end; id.v = segm->getEndPoint(); vertexIds.push_back(id); } else if (g->getTypeId() == Part::GeomArcOfParabola::getClassTypeId()) { const Part::GeomArcOfParabola *segm = dynamic_cast<const Part::GeomArcOfParabola*>(g); VertexIds id; id.GeoId = (int)i; id.PosId = Sketcher::start; id.v = segm->getStartPoint(); vertexIds.push_back(id); id.GeoId = (int)i; id.PosId = Sketcher::end; id.v = segm->getEndPoint(); vertexIds.push_back(id); } } std::set<ConstraintIds, Constraint_Less> coincidences; double prec = Precision::Confusion(); QVariant v = ui->comboBoxTolerance->itemData(ui->comboBoxTolerance->currentIndex()); if (v.isValid()) prec = v.toDouble(); else prec = QLocale::system().toDouble(ui->comboBoxTolerance->currentText()); std::sort(vertexIds.begin(), vertexIds.end(), Vertex_Less(prec)); std::vector<VertexIds>::iterator vt = vertexIds.begin(); Vertex_EqualTo pred(prec); while (vt < vertexIds.end()) { // get first item whose adjacent element has the same vertex coordinates vt = std::adjacent_find(vt, vertexIds.end(), pred); if (vt < vertexIds.end()) { std::vector<VertexIds>::iterator vn; for (vn = vt+1; vn != vertexIds.end(); ++vn) { if (pred(*vt,*vn)) { ConstraintIds id; id.v = vt->v; id.First = vt->GeoId; id.FirstPos = vt->PosId; id.Second = vn->GeoId; id.SecondPos = vn->PosId; coincidences.insert(id); } else { break; } } vt = vn; } } std::vector<Sketcher::Constraint*> constraint = sketch->Constraints.getValues(); for (std::vector<Sketcher::Constraint*>::iterator it = constraint.begin(); it != constraint.end(); ++it) { if ((*it)->Type == Sketcher::Coincident) { ConstraintIds id; id.First = (*it)->First; id.FirstPos = (*it)->FirstPos; id.Second = (*it)->Second; id.SecondPos = (*it)->SecondPos; std::set<ConstraintIds, Constraint_Less>::iterator pos = coincidences.find(id); if (pos != coincidences.end()) { coincidences.erase(pos); } } } this->vertexConstraints.clear(); this->vertexConstraints.reserve(coincidences.size()); std::vector<Base::Vector3d> points; points.reserve(coincidences.size()); for (std::set<ConstraintIds, Constraint_Less>::iterator it = coincidences.begin(); it != coincidences.end(); ++it) { this->vertexConstraints.push_back(*it); points.push_back(it->v); } hidePoints(); if (this->vertexConstraints.empty()) { QMessageBox::information(this, tr("No missing coincidences"), tr("No missing coincidences found")); ui->fixButton->setEnabled(false); } else { showPoints(points); QMessageBox::warning(this, tr("Missing coincidences"), tr("%1 missing coincidences found").arg(this->vertexConstraints.size())); ui->fixButton->setEnabled(true); } }
bool BrowseTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_UNUSED(role); if (!index.isValid()) { return false; } qDebug() << "BrowseTableModel::setData(" << index.data() << ")"; int row = index.row(); int col = index.column(); mixxx::TrackMetadata trackMetadata; // set tagger information trackMetadata.setArtist(this->index(row, COLUMN_ARTIST).data().toString()); trackMetadata.setTitle(this->index(row, COLUMN_TITLE).data().toString()); trackMetadata.setAlbum(this->index(row, COLUMN_ALBUM).data().toString()); trackMetadata.setKey(this->index(row, COLUMN_KEY).data().toString()); trackMetadata.setBpm(mixxx::Bpm(this->index(row, COLUMN_BPM).data().toDouble())); trackMetadata.setComment(this->index(row, COLUMN_COMMENT).data().toString()); trackMetadata.setTrackNumber(this->index(row, COLUMN_TRACK_NUMBER).data().toString()); trackMetadata.setYear(this->index(row, COLUMN_YEAR).data().toString()); trackMetadata.setGenre(this->index(row, COLUMN_GENRE).data().toString()); trackMetadata.setComposer(this->index(row, COLUMN_COMPOSER).data().toString()); trackMetadata.setAlbumArtist(this->index(row, COLUMN_ALBUMARTIST).data().toString()); trackMetadata.setGrouping(this->index(row, COLUMN_GROUPING).data().toString()); // check if one the item were edited if (col == COLUMN_ARTIST) { trackMetadata.setArtist(value.toString()); } else if (col == COLUMN_TITLE) { trackMetadata.setTitle(value.toString()); } else if (col == COLUMN_ALBUM) { trackMetadata.setAlbum(value.toString()); } else if (col == COLUMN_BPM) { trackMetadata.setBpm(mixxx::Bpm(value.toDouble())); } else if (col == COLUMN_KEY) { trackMetadata.setKey(value.toString()); } else if (col == COLUMN_TRACK_NUMBER) { trackMetadata.setTrackNumber(value.toString()); } else if (col == COLUMN_COMMENT) { trackMetadata.setComment(value.toString()); } else if (col == COLUMN_GENRE) { trackMetadata.setGenre(value.toString()); } else if (col == COLUMN_COMPOSER) { trackMetadata.setComposer(value.toString()); } else if (col == COLUMN_YEAR) { trackMetadata.setYear(value.toString()); } else if (col == COLUMN_ALBUMARTIST) { trackMetadata.setAlbumArtist(value.toString()); } else if (col == COLUMN_GROUPING) { trackMetadata.setGrouping(value.toString()); } else { qWarning() << "BrowseTableModel::setData(): no tagger column"; return false; } QStandardItem* item = itemFromIndex(index); QString track_location(getTrackLocation(index)); if (OK == mixxx::taglib::writeTrackMetadataIntoFile(trackMetadata, track_location)) { // Modify underlying interalPointer object item->setText(value.toString()); item->setToolTip(item->text()); return true; } else { // reset to old value in error item->setText(index.data().toString()); item->setToolTip(item->text()); QMessageBox::critical( 0, tr("Mixxx Library"), tr("Could not update file metadata.") + "\n" +track_location); return false; } }
QString ConversionUtil::toJsonString(const QVariant &variant, Options options) { switch (variant.type()) { case QVariant::Bool: return variant.toBool() ? "true" : "false"; case QVariant::Int: return QString::number(variant.toInt()); case QVariant::UInt: return QString::number(variant.toUInt()); case QVariant::Double: return QString::number(variant.toDouble()); case QVariant::String: return variant.toString().isEmpty() ? QString() : jsString(variant.toString()); case QVariant::List: { QStringList stringList; for (const QVariant &item : variant.toList()) { stringList.append(ConversionUtil::toJsonString(item)); } if (stringList.isEmpty()) { return QString(); } else { return "[ " + stringList.join(", ") + " ]"; } } case QVariant::StringList: { QStringList stringList; for (const QString &string : variant.toStringList()) { stringList.append(jsString(string)); } if (stringList.isEmpty()) { return QString(); } else { return "[ " + stringList.join(", ") + " ]"; } } case QVariant::DateTime: return QString::number(variant.toDateTime().toMSecsSinceEpoch()); case QVariant::Map: { QStringList stringList; QVariantMap map = variant.toMap(); for (const QString &key : map.keys()) { QVariant value = map[key]; QString jsonString = toJsonString(value, options); if (!jsonString.isEmpty()) { if (options & IncludeTypeInfo) { stringList.append(QString("%1: [ %2, %3, %4 ]") .arg(jsString(key), QString::number(value.type()), QString::number(value.userType()), jsonString)); } else { stringList.append(QString("%1: %2").arg(jsString(key), jsonString)); } } } return stringList.isEmpty() ? QString() : "{ " + stringList.join(", ") + " }"; } case QVariant::UserType: { MetaTypeRegistry::JsonConverters converters = MetaTypeRegistry::jsonConverters(QMetaType::typeName(variant.userType())); if (converters.typeToJsonStringConverter) { return converters.typeToJsonStringConverter(variant); } else { const char *typeName = QMetaType::typeName(variant.userType()); if (typeName) { LogUtil::logError("User type not serializable: %1", typeName); } else { LogUtil::logError("Unknown user type: %1", QString::number(variant.userType())); } return QString(); } } default: LogUtil::logError("Unknown type: %1", variant.typeName()); return QString(); } }
/** * Searches for a widget and its value in the argument object \a args * to returns its value as Python object. * In the case it fails 0 is returned. */ PyObject *PyResource::value(PyObject *args) { char *psName; char *psProperty; if (!PyArg_ParseTuple(args, "ss", &psName, &psProperty)) // convert args: Python->C return NULL; // NULL triggers exception QVariant v; if (myDlg) { QList<QWidget*> list = myDlg->findChildren<QWidget*>(); QList<QWidget*>::const_iterator it = list.begin(); QObject *obj; bool fnd = false; while ( it != list.end() ) { obj = *it; ++it; if (obj->objectName() == QLatin1String(psName)) { fnd = true; v = obj->property(psProperty); break; } } if ( !fnd ) qWarning( "'%s' not found.\n", psName ); } PyObject *pItem=0; switch (v.type()) { case QVariant::StringList: { QStringList str = v.toStringList(); int nSize = str.count(); PyObject* slist = PyList_New(nSize); for (int i=0; i<nSize;++i) { PyObject* item = PyString_FromString(str[i].toAscii()); PyList_SetItem(slist, i, item); } } break; case QVariant::ByteArray: break; case QVariant::String: pItem = PyString_FromString(v.toString().toAscii()); break; case QVariant::Double: pItem = PyFloat_FromDouble(v.toDouble()); break; case QVariant::Bool: pItem = PyInt_FromLong(v.toBool() ? 1 : 0); break; case QVariant::UInt: pItem = PyLong_FromLong(v.toUInt()); break; case QVariant::Int: pItem = PyInt_FromLong(v.toInt()); break; default: pItem = PyString_FromString(""); break; } return pItem; }