enum SetResponse dspInventoryAvailabilityByParameterList::set(const ParameterList &pParams) { QVariant param; bool valid; param = pParams.value("classcode_id", &valid); if (valid) { _parameter->setType(ParameterGroup::ClassCode); _parameter->setId(param.toInt()); } param = pParams.value("classcode_pattern", &valid); if (valid) { _parameter->setType(ParameterGroup::ClassCode); _parameter->setPattern(param.toString()); } param = pParams.value("classcode", &valid); if (valid) _parameter->setType(ParameterGroup::ClassCode); param = pParams.value("plancode_id", &valid); if (valid) { _parameter->setType(ParameterGroup::PlannerCode); _parameter->setId(param.toInt()); } param = pParams.value("plancode_pattern", &valid); if (valid) { _parameter->setType(ParameterGroup::PlannerCode); _parameter->setPattern(param.toString()); } param = pParams.value("plancode", &valid); if (valid) _parameter->setType(ParameterGroup::PlannerCode); param = pParams.value("itemgrp_id", &valid); if (valid) { _parameter->setType(ParameterGroup::ItemGroup); _parameter->setId(param.toInt()); } param = pParams.value("itemgrp_pattern", &valid); if (valid) { _parameter->setType(ParameterGroup::ItemGroup); _parameter->setPattern(param.toString()); } param = pParams.value("itemgrp", &valid); if (valid) _parameter->setType(ParameterGroup::ItemGroup); switch (_parameter->type()) { case ParameterGroup::ClassCode: setWindowTitle(tr("Inventory Availability by Class Code")); break; case ParameterGroup::PlannerCode: setWindowTitle(tr("Inventory Availability by Planner Code")); break; case ParameterGroup::ItemGroup: setWindowTitle(tr("Inventory Availability by Item Group")); break; default: break; } if (pParams.inList("run")) { sFillList(); return NoError_Run; } return NoError; }
enum SetResponse user::set(const ParameterList &pParams) { XDialog::set(pParams); QVariant param; bool valid; param = pParams.value("crmacct_id", &valid); if (valid) _crmacctid = param.toInt(); param = pParams.value("username", &valid); if (valid) _cUsername = param.toString(); if (! _cUsername.isEmpty() || _crmacctid > 0) if (! sPopulate()) return UndefinedError; param = pParams.value("mode", &valid); if (valid) { if (param.toString() == "new") { _mode = cNew; _module->setCurrentIndex(0); sModuleSelected(_module->itemText(0)); if (_cUsername.isEmpty()) _username->setFocus(); else { _username->setEnabled(false); if(omfgThis->useCloud() && _cUsername.endsWith("_" + omfgThis->company())) _username->setText(_cUsername.left(_cUsername.length() - (omfgThis->company().length()+1))); else _username->setText(_cUsername); _active->setFocus(); sCheck(); } if (_metrics->boolean("MultiWhs")) populateSite(); } else if (param.toString() == "edit") { _mode = cEdit; _username->setEnabled(FALSE); _save->setFocus(); } else if (param.toString() == "view") { _mode = cView; _close->setText(tr("&Close")); _save->hide(); _close->setFocus(); } } bool canEdit = (cNew == _mode || cEdit == _mode); _active->setEnabled(canEdit); _add->setEnabled(canEdit); _addAll->setEnabled(canEdit); _addGroup->setEnabled(canEdit); // _addSite->setEnabled(canEdit); _agent->setEnabled(canEdit); _allSites->setEnabled(canEdit); _email->setEnabled(canEdit); _employee->setReadOnly(! canEdit); _enhancedAuth->setEnabled(canEdit); _exportContents->setEnabled(canEdit); _initials->setEnabled(canEdit); _locale->setEnabled(canEdit); _passwd->setEnabled(canEdit); _properName->setEnabled(canEdit); _revoke->setEnabled(canEdit); _revokeAll->setEnabled(canEdit); _revokeGroup->setEnabled(canEdit); // _revokeSite->setEnabled(canEdit); _save->setEnabled(canEdit); _selectedSites->setEnabled(canEdit); _verify->setEnabled(canEdit); if (! canEdit) { _available->setSelectionMode(QAbstractItemView::NoSelection); _availableGroup->setSelectionMode(QAbstractItemView::NoSelection); _availableSite->setSelectionMode(QAbstractItemView::NoSelection); _granted->setSelectionMode(QAbstractItemView::NoSelection); _grantedGroup->setSelectionMode(QAbstractItemView::NoSelection); _grantedSite->setSelectionMode(QAbstractItemView::NoSelection); } if(canEdit) { XSqlQuery begin; _inTransaction = begin.exec("BEGIN;"); } return NoError; }
void readChoices() { QVariant value = settings->defaultValue(QStringLiteral("testChoices")); QCOMPARE(value.toString(), QStringLiteral("one")); }
void KxMenuItemWidget::paintEvent(QPaintEvent *event) { // Do not draw invisible menu items if(!fMenuItem->isVisible()) return; QStylePainter painter(this); QStyleOptionMenuItem opt = getStyleOption(); QRect boxRect; bool inOptionBox = false; QWidget *q = parentWidget(); const int hmargin = q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q), iconWidth = q->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q); if(!fMenuItem->isSeparator()) { if(fMenuItem->hasOptionBox()) { boxRect.setRect(rect().right() - hmargin - iconWidth, rect().top(), iconWidth, rect().height()); QPoint p = QCursor::pos(); p = mapFromGlobal(p); if(boxRect.contains(p)) { inOptionBox = true; } else { // Subtract option box rect from style option rect int newRight = opt.rect.right() - iconWidth - hmargin; opt.rect.setRight(newRight); } } } // Draw general menu item opt.rect.adjust(0, 0, -1, 0); painter.drawControl(QStyle::CE_MenuItem, opt); // Draw shortcut QKeySequence shortcutSeq = fMenuItem->shortcut(); if(!shortcutSeq.isEmpty()) { // shortcut bounds QRect scRect = opt.rect; QString shortcut = shortcutSeq.toString(QKeySequence::NativeText); QMenu *menu = qobject_cast<QMenu *>(parentWidget()); Q_ASSERT(menu != NULL); int shortcutWidth = 12; // default value in case there is no font if ( menu ) { QFontMetrics metrics(fMenuItem->font().resolve(menu->font())); shortcutWidth = metrics.width(shortcut); } scRect.setLeft(scRect.right() - shortcutWidth); if(inOptionBox || !fMenuItem->hasOptionBox()) { scRect.translate(-iconWidth, 0); } scRect.translate(-kShortcutRightMargin, 0); painter.drawItemText(scRect, Qt::AlignRight | Qt::AlignVCenter, palette(), true, shortcut); } // Draw option box if(!fMenuItem->isSeparator() && fMenuItem->hasOptionBox()) { QIcon* boxIcon = NULL; QVariant v = fMenuItem->optionBoxAction()->property( "optionBoxIcon" ); if ( v.isValid() ) { QString optionBoxIcon; optionBoxIcon = v.toString(); boxIcon = KxQtHelper::createIcon( optionBoxIcon ); } if ( boxIcon == NULL ) { boxIcon = new QIcon(":/optionBox.png"); } boxRect.setRect(rect().right() - hmargin - iconWidth, rect().top()+(rect().height()-iconWidth)/2, iconWidth, iconWidth); boxIcon->paint(&painter, boxRect, Qt::AlignCenter, fMenuItem->isEnabled() ? QIcon::Normal : QIcon::Disabled); delete boxIcon; } }
enum SetResponse itemPricingSchedule::set(const ParameterList &pParams) { XDialog::set(pParams); QVariant param; bool valid; param = pParams.value("mode", &valid); if (valid) { if (param.toString() == "new") { _mode = cNew; _name->setFocus(); } else if (param.toString() == "edit") { _mode = cEdit; _save->setFocus(); } else if (param.toString() == "copy") { _mode = cCopy; _name->setFocus(); } else if (param.toString() == "view") { _mode = cView; _name->setEnabled(FALSE); _descrip->setEnabled(FALSE); _dates->setEnabled(FALSE); _currency->setEnabled(FALSE); _new->setEnabled(FALSE); _close->setText(tr("&Close")); _save->hide(); _close->setFocus(); } } param = pParams.value("ipshead_id", &valid); if (valid) { _ipsheadid = param.toInt(); populate(); } if ( (_mode == cNew) || (_mode == cEdit) || (_mode == cCopy) ) { connect(_ipsitem, SIGNAL(valid(bool)), _edit, SLOT(setEnabled(bool))); connect(_ipsitem, SIGNAL(valid(bool)), _delete, SLOT(setEnabled(bool))); connect(_ipsitem, SIGNAL(itemSelected(int)), _edit, SLOT(animateClick())); } if ( (_mode == cNew) ) { q.exec("SELECT NEXTVAL('ipshead_ipshead_id_seq') AS ipshead_id;"); if (q.first()) _ipsheadid = q.value("ipshead_id").toInt(); else if (q.lastError().type() != QSqlError::NoError) { systemError(this, _rejectedMsg.arg(q.lastError().databaseText()), __FILE__, __LINE__); reject(); return UndefinedError; } } return NoError; }
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::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 JArchive::writeValue(const QString &key,const QVariant &value,bool compress) { //This is how we used to do it, in version 2 /* if (value.type()==QVariant::StringList) { QStringList list=value.toStringList(); QString str="StringList::"; for (int i=0; i<list.count(); i++) { str+=QString("{%1}").arg(list[i].count()); str+=list[i]; } return writeValue(key,str); } else { QByteArray tmp=value.toString().toAscii(); return writeData(key,tmp,false,"Value"); } }*/ { //as of version 3 if (value.type()==QVariant::StringList) { QByteArray tmp; tmp.append("StringList"); tmp.append((char)0); QStringList val=value.toStringList(); for (int ii=0; ii<val.count(); ii++) { tmp.append(val[ii].toAscii()); if (ii+1<val.count()) tmp.append((char)0); } return writeData(key,tmp,compress,"Value"); } else if (value.type()==QVariant::Image) { QImage img=value.value<QImage>(); QString img_format="JPG"; //if (img.hasAlphaChannel()) img_format="PNG"; img_format="PNG"; //for now, use only PNG, because it seems that the static MAC version of the rwclient cannot handle JPG. QByteArray tmp; tmp.append("Image::"+img_format); tmp.append((char)0); QBuffer buffer(&tmp); buffer.open(QIODevice::Append); img.save(&buffer,img_format.toAscii().data(),99); buffer.close(); return writeData(key,tmp,compress,"Value"); } else if (value.type()==QVariant::ByteArray) { QByteArray data=value.toByteArray(); QByteArray tmp; tmp.append("ByteArray"); tmp.append((char)0); tmp.append(data); return writeData(key,tmp,compress,"Value"); } else if (value.type()==QVariant::PointF) { QPointF vvv=value.toPointF(); QByteArray tmp; tmp.append("PointF"); tmp.append((char)0); tmp.append(QString("%1,%2").arg(vvv.x()).arg(vvv.y()).toAscii()); return writeData(key,tmp,compress,"Value"); } else if (value.type()==QVariant::DateTime) { //added on 1/11/2012 to handle milliseconds! QByteArray tmp; tmp.append("DateTime"); tmp.append((char)0); tmp.append(value.toDateTime().toString("yyyy-MM-ddThh:mm:ss.zzz")); return writeData(key,tmp,compress,"Value"); } else if (value.type()==QVariant::Time) { //added on 1/11/2012 to handle milliseconds! QByteArray tmp; tmp.append("Time"); tmp.append((char)0); tmp.append(value.toTime().toString("hh:mm:ss.zzz")); return writeData(key,tmp,compress,"Value"); } else { QByteArray tmp; tmp.append(value.typeName()); tmp.append((char)0); tmp.append(value.toString().toAscii()); return writeData(key,tmp,compress,"Value"); } } }
void QgsEllipseSymbolLayer::renderPoint( QPointF point, QgsSymbolRenderContext &context ) { double scaledWidth = mSymbolWidth; double scaledHeight = mSymbolHeight; if ( mDataDefinedProperties.hasActiveProperties() ) { bool ok; context.setOriginalValueVariable( mStrokeWidth ); QVariant exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyStrokeWidth, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { double width = exprVal.toDouble( &ok ); if ( ok ) { width = context.renderContext().convertToPainterUnits( width, mStrokeWidthUnit, mStrokeWidthMapUnitScale ); mPen.setWidthF( width ); } } context.setOriginalValueVariable( QgsSymbolLayerUtils::encodePenStyle( mStrokeStyle ) ); exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyStrokeStyle, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { mPen.setStyle( QgsSymbolLayerUtils::decodePenStyle( exprVal.toString() ) ); } context.setOriginalValueVariable( QgsSymbolLayerUtils::encodePenJoinStyle( mPenJoinStyle ) ); exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyJoinStyle, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { mPen.setJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( exprVal.toString() ) ); } context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mColor ) ); mBrush.setColor( mDataDefinedProperties.valueAsColor( QgsSymbolLayer::PropertyFillColor, context.renderContext().expressionContext(), mColor ) ); context.setOriginalValueVariable( QgsSymbolLayerUtils::encodeColor( mStrokeColor ) ); mPen.setColor( mDataDefinedProperties.valueAsColor( QgsSymbolLayer::PropertyStrokeColor, context.renderContext().expressionContext(), mStrokeColor ) ); if ( mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyWidth ) || mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyHeight ) || mDataDefinedProperties.isActive( QgsSymbolLayer::PropertyName ) ) { QString symbolName = mSymbolName; context.setOriginalValueVariable( mSymbolName ); exprVal = mDataDefinedProperties.value( QgsSymbolLayer::PropertyName, context.renderContext().expressionContext() ); if ( exprVal.isValid() ) { symbolName = exprVal.toString(); } preparePath( symbolName, context, &scaledWidth, &scaledHeight, context.feature() ); } } //offset and rotation bool hasDataDefinedRotation = false; QPointF offset; double angle = 0; calculateOffsetAndRotation( context, scaledWidth, scaledHeight, hasDataDefinedRotation, offset, angle ); QPainter *p = context.renderContext().painter(); if ( !p ) { return; } QMatrix transform; transform.translate( point.x() + offset.x(), point.y() + offset.y() ); if ( !qgsDoubleNear( angle, 0.0 ) ) { transform.rotate( angle ); } p->setPen( mPen ); p->setBrush( mBrush ); p->drawPath( transform.map( mPainterPath ) ); }
void UBKeyboardPalette::keyboardPaletteButtonSizeChanged(QVariant size) { setKeyButtonSize(size.toString()); }
void QgsLayoutTable::render( QgsLayoutItemRenderContext &context, const QRectF &, const int frameIndex ) { bool emptyTable = mTableContents.length() == 0; if ( emptyTable && mEmptyTableMode == QgsLayoutTable::HideTable ) { //empty table set to hide table mode, so don't draw anything return; } if ( !mLayout->renderContext().isPreviewRender() ) { //exporting composition, so force an attribute refresh //we do this in case vector layer has changed via an external source (e.g., another database user) refreshAttributes(); } //calculate which rows to show in this frame QPair< int, int > rowsToShow = rowRange( frameIndex ); double gridSizeX = mShowGrid && mVerticalGrid ? mGridStrokeWidth : 0; double gridSizeY = mShowGrid && mHorizontalGrid ? mGridStrokeWidth : 0; double cellHeaderHeight = QgsLayoutUtils::fontAscentMM( mHeaderFont ) + 2 * mCellMargin; double cellBodyHeight = QgsLayoutUtils::fontAscentMM( mContentFont ) + 2 * mCellMargin; QRectF cell; //calculate whether a header is required bool drawHeader = ( ( mHeaderMode == QgsLayoutTable::FirstFrame && frameIndex < 1 ) || ( mHeaderMode == QgsLayoutTable::AllFrames ) ); //calculate whether drawing table contents is required bool drawContents = !( emptyTable && mEmptyTableMode == QgsLayoutTable::ShowMessage ); int numberRowsToDraw = rowsToShow.second - rowsToShow.first; int numberEmptyRows = 0; if ( drawContents && mShowEmptyRows ) { numberRowsToDraw = rowsVisible( frameIndex, rowsToShow.first, true ); numberEmptyRows = numberRowsToDraw - rowsToShow.second + rowsToShow.first; } bool mergeCells = false; if ( emptyTable && mEmptyTableMode == QgsLayoutTable::ShowMessage ) { //draw a merged row for the empty table message numberRowsToDraw++; rowsToShow.second++; mergeCells = true; } QPainter *p = context.renderContext().painter(); p->save(); // painter is scaled to dots, so scale back to layout units p->scale( context.renderContext().scaleFactor(), context.renderContext().scaleFactor() ); //draw the text p->setPen( Qt::SolidLine ); double currentX = gridSizeX; double currentY = gridSizeY; if ( drawHeader ) { //draw the headers int col = 0; for ( const QgsLayoutTableColumn *column : qgis::as_const( mColumns ) ) { //draw background p->save(); p->setPen( Qt::NoPen ); p->setBrush( backgroundColor( -1, col ) ); p->drawRect( QRectF( currentX, currentY, mMaxColumnWidthMap[col] + 2 * mCellMargin, cellHeaderHeight ) ); p->restore(); currentX += mCellMargin; Qt::TextFlag textFlag = static_cast< Qt::TextFlag >( 0 ); if ( column->width() <= 0 ) { //automatic column width, so we use the Qt::TextDontClip flag when drawing contents, as this works nicer for italicised text //which may slightly exceed the calculated width //if column size was manually set then we do apply text clipping, to avoid painting text outside of columns width textFlag = Qt::TextDontClip; } cell = QRectF( currentX, currentY, mMaxColumnWidthMap[col], cellHeaderHeight ); //calculate alignment of header Qt::AlignmentFlag headerAlign = Qt::AlignLeft; switch ( mHeaderHAlignment ) { case FollowColumn: headerAlign = column->hAlignment(); break; case HeaderLeft: headerAlign = Qt::AlignLeft; break; case HeaderCenter: headerAlign = Qt::AlignHCenter; break; case HeaderRight: headerAlign = Qt::AlignRight; break; } QgsLayoutUtils::drawText( p, cell, column->heading(), mHeaderFont, mHeaderFontColor, headerAlign, Qt::AlignVCenter, textFlag ); currentX += mMaxColumnWidthMap[ col ]; currentX += mCellMargin; currentX += gridSizeX; col++; } currentY += cellHeaderHeight; currentY += gridSizeY; } //now draw the body cells int rowsDrawn = 0; if ( drawContents ) { //draw the attribute values for ( int row = rowsToShow.first; row < rowsToShow.second; ++row ) { rowsDrawn++; currentX = gridSizeX; int col = 0; //calculate row height double rowHeight = mMaxRowHeightMap[row + 1] + 2 * mCellMargin; for ( const QgsLayoutTableColumn *column : qgis::as_const( mColumns ) ) { //draw background p->save(); p->setPen( Qt::NoPen ); p->setBrush( backgroundColor( row, col ) ); p->drawRect( QRectF( currentX, currentY, mMaxColumnWidthMap[col] + 2 * mCellMargin, rowHeight ) ); p->restore(); // currentY = gridSize; currentX += mCellMargin; QVariant cellContents = mTableContents.at( row ).at( col ); QString str = cellContents.toString(); Qt::TextFlag textFlag = static_cast< Qt::TextFlag >( 0 ); if ( column->width() <= 0 && mWrapBehavior == TruncateText ) { //automatic column width, so we use the Qt::TextDontClip flag when drawing contents, as this works nicer for italicised text //which may slightly exceed the calculated width //if column size was manually set then we do apply text clipping, to avoid painting text outside of columns width textFlag = Qt::TextDontClip; } else if ( textRequiresWrapping( str, column->width(), mContentFont ) ) { str = wrappedText( str, column->width(), mContentFont ); } cell = QRectF( currentX, currentY, mMaxColumnWidthMap[col], rowHeight ); QgsLayoutUtils::drawText( p, cell, str, mContentFont, mContentFontColor, column->hAlignment(), column->vAlignment(), textFlag ); currentX += mMaxColumnWidthMap[ col ]; currentX += mCellMargin; currentX += gridSizeX; col++; } currentY += rowHeight; currentY += gridSizeY; } } if ( numberRowsToDraw > rowsDrawn ) { p->save(); p->setPen( Qt::NoPen ); //draw background of empty rows for ( int row = rowsDrawn; row < numberRowsToDraw; ++row ) { currentX = gridSizeX; int col = 0; if ( mergeCells ) { p->setBrush( backgroundColor( row + 10000, 0 ) ); p->drawRect( QRectF( gridSizeX, currentY, mTableSize.width() - 2 * gridSizeX, cellBodyHeight ) ); } else { for ( QgsLayoutTableColumn *column : qgis::as_const( mColumns ) ) { Q_UNUSED( column ); //draw background //we use a bit of a hack here - since we don't want these extra blank rows to match the firstrow/lastrow rule, add 10000 to row number p->setBrush( backgroundColor( row + 10000, col ) ); p->drawRect( QRectF( currentX, currentY, mMaxColumnWidthMap[col] + 2 * mCellMargin, cellBodyHeight ) ); // currentY = gridSize; currentX += mMaxColumnWidthMap[ col ] + 2 * mCellMargin; currentX += gridSizeX; col++; } } currentY += cellBodyHeight + gridSizeY; } p->restore(); } //and the borders if ( mShowGrid ) { QPen gridPen; gridPen.setWidthF( mGridStrokeWidth ); gridPen.setColor( mGridColor ); gridPen.setJoinStyle( Qt::MiterJoin ); p->setPen( gridPen ); if ( mHorizontalGrid ) { drawHorizontalGridLines( p, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader ); } if ( mVerticalGrid ) { drawVerticalGridLines( p, mMaxColumnWidthMap, rowsToShow.first, rowsToShow.second + numberEmptyRows, drawHeader, mergeCells ); } } //special case - no records and table is set to ShowMessage mode if ( emptyTable && mEmptyTableMode == QgsLayoutTable::ShowMessage ) { double messageX = gridSizeX + mCellMargin; double messageY = gridSizeY + ( drawHeader ? cellHeaderHeight + gridSizeY : 0 ); cell = QRectF( messageX, messageY, mTableSize.width() - messageX, cellBodyHeight ); QgsLayoutUtils::drawText( p, cell, mEmptyTableMessage, mContentFont, mContentFontColor, Qt::AlignHCenter, Qt::AlignVCenter, static_cast< Qt::TextFlag >( 0 ) ); } p->restore(); }
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; case ProxyUse: settings.setValue("fUseProxy", value.toBool()); ApplyProxySettings(); break; case ProxyIP: { proxyType proxy; proxy = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); CNetAddr addr(value.toString().toStdString()); proxy.SetIP(addr); settings.setValue("addrProxy", proxy.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxyPort: { proxyType proxy; proxy = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); proxy.SetPort(value.toInt()); settings.setValue("addrProxy", proxy.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case Fee: nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", (qint64) nTransactionFee); emit transactionFeeChanged(nTransactionFee); break; case ReserveBalance: nReserveBalance = value.toLongLong(); settings.setValue("nReserveBalance", (qint64) nReserveBalance); emit reserveBalanceChanged(nReserveBalance); break; case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case Language: settings.setValue("language", value); break; case CoinControlFeatures: { fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); emit coinControlFeaturesChanged(fCoinControlFeatures); } break; case MinimizeCoinAge: fMinimizeCoinAge = value.toBool(); settings.setValue("fMinimizeCoinAge", fMinimizeCoinAge); break; case UseBlackTheme: fUseBlackTheme = value.toBool(); settings.setValue("fUseBlackTheme", fUseBlackTheme); break; case DarksendRounds: nDarksendRounds = value.toInt(); settings.setValue("nDarksendRounds", nDarksendRounds); emit darksendRoundsChanged(nDarksendRounds); break; case anonymizeGravitonAmount: nAnonymizeGravitonAmount = value.toInt(); settings.setValue("nAnonymizeGravitonAmount", nAnonymizeGravitonAmount); emit anonymizeGravitonAmountChanged(nAnonymizeGravitonAmount); break; default: break; } } emit dataChanged(index, index); return successful; }
enum SetResponse location::set(const ParameterList &pParams) { XDialog::set(pParams); QVariant param; bool valid; param = pParams.value("location_id", &valid); if (valid) { _locationid = param.toInt(); populate(); } param = pParams.value("mode", &valid); if (valid) { if (param.toString() == "new") { _mode = cNew; q.exec("SELECT NEXTVAL('location_location_id_seq') AS location_id;"); if (q.first()) _locationid = q.value("location_id").toInt(); else { systemError(this, tr("A System Error occurred at %1::%2.") .arg(__FILE__) .arg(__LINE__) ); return UndefinedError; } _warehouse->setFocus(); } else if (param.toString() == "edit") { _mode = cEdit; _warehouse->setEnabled(FALSE); _location->setFocus(); } else if (param.toString() == "view") { _mode = cView; _warehouse->setEnabled(FALSE); _whsezone->setEnabled(FALSE); _aisle->setEnabled(FALSE); _rack->setEnabled(FALSE); _bin->setEnabled(FALSE); _location->setEnabled(FALSE); _netable->setEnabled(FALSE); _restricted->setEnabled(FALSE); _description->setEnabled(FALSE); _locitem->setEnabled(FALSE); _save->hide(); _new->hide(); _delete->hide(); _close->setText(tr("&Close")); _close->setFocus(); } } param = pParams.value("warehous_id", &valid); if (valid) { _warehouse->setId(param.toInt()); _warehouse->setEnabled(FALSE); } return NoError; }
QWidget* QmitkPropertyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option , const QModelIndex &index) const { QVariant data = index.data(Qt::EditRole); QVariant displayData = index.data(Qt::DisplayRole); QString name = index.model()->data(index.model()->index(index.row(), index.column()-1)).value<QString>(); if(data.isValid()) { QWidget* editorWidget = NULL; if(data.type() == QVariant::Color) { QPushButton* colorBtn = new QPushButton(parent); QColor color = data.value<QColor>(); QColor result = QColorDialog::getColor(color); if(result.isValid()) { QPalette palette = colorBtn->palette(); palette.setColor(QPalette::Button, result); colorBtn->setPalette(palette); colorBtn->setStyleSheet(QString("background-color: %1;foreground-color: %1; border-style: none;").arg(result.name())); //colorBtn->setFlat(true); } // QColorDialog closed by 'Cancel' button, use the old property color else { QPalette palette = colorBtn->palette(); palette.setColor(QPalette::Button, color); colorBtn->setPalette(palette); colorBtn->setStyleSheet(QString("background-color: %1;foreground-color: %1; border-style: none;").arg(color.name())); } connect(colorBtn, SIGNAL(pressed()), this, SLOT(commitAndCloseEditor())); editorWidget = colorBtn; } /* else if(data.type() == QVariant::Bool) { QCheckBox *visibilityCheckBox = new QCheckBox(parent); connect(visibilityCheckBox, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor())); return visibilityCheckBox; }*/ else if(data.type() == QVariant::Int) { QSpinBox* spinBox = new QSpinBox(parent); spinBox->setSingleStep(1); spinBox->setMinimum(std::numeric_limits<int>::min()); spinBox->setMaximum(std::numeric_limits<int>::max()); editorWidget = spinBox; } // see qt documentation. cast is correct, it would be obsolete if we // store doubles else if(static_cast<QMetaType::Type>(data.type()) == QMetaType::Float) { QDoubleSpinBox* spinBox = new QDoubleSpinBox(parent); spinBox->setDecimals(2); spinBox->setSingleStep(0.1); if(name == "opacity") { spinBox->setMinimum(0.0); spinBox->setMaximum(1.0); } else { spinBox->setMinimum(std::numeric_limits<float>::min()); spinBox->setMaximum(std::numeric_limits<float>::max()); } editorWidget = spinBox; } else if(data.type() == QVariant::StringList) { QStringList entries = data.value<QStringList>(); QComboBox* comboBox = new QComboBox(parent); comboBox->setEditable(false); comboBox->addItems(entries); editorWidget = comboBox; } else { editorWidget = QStyledItemDelegate::createEditor(parent, option, index); } if ( editorWidget ) { // install event filter editorWidget->installEventFilter( const_cast<QmitkPropertyDelegate*>(this) ); } return editorWidget; } else return new QLabel(displayData.toString(), parent); }
int QgsAtlasComposition::updateFeatures() { //needs to be called when layer, filter, sort changes if ( !mCoverageLayer ) { return 0; } QgsExpressionContext expressionContext = createExpressionContext(); updateFilenameExpression(); // select all features with all attributes QgsFeatureRequest req; QScopedPointer<QgsExpression> filterExpression; if ( mFilterFeatures && !mFeatureFilter.isEmpty() ) { filterExpression.reset( new QgsExpression( mFeatureFilter ) ); if ( filterExpression->hasParserError() ) { mFilterParserError = filterExpression->parserErrorString(); return 0; } //filter good to go req.setFilterExpression( mFeatureFilter ); } mFilterParserError = QString(); QgsFeatureIterator fit = mCoverageLayer->getFeatures( req ); QScopedPointer<QgsExpression> nameExpression; if ( !mPageNameExpression.isEmpty() ) { nameExpression.reset( new QgsExpression( mPageNameExpression ) ); if ( nameExpression->hasParserError() ) { nameExpression.reset( nullptr ); } nameExpression->prepare( &expressionContext ); } // We cannot use nextFeature() directly since the feature pointer is rewinded by the rendering process // We thus store the feature ids for future extraction QgsFeature feat; mFeatureIds.clear(); mFeatureKeys.clear(); int sortIdx = mCoverageLayer->fieldNameIndex( mSortKeyAttributeName ); while ( fit.nextFeature( feat ) ) { expressionContext.setFeature( feat ); QString pageName; if ( !nameExpression.isNull() ) { QVariant result = nameExpression->evaluate( &expressionContext ); if ( nameExpression->hasEvalError() ) { QgsMessageLog::logMessage( tr( "Atlas name eval error: %1" ).arg( nameExpression->evalErrorString() ), tr( "Composer" ) ); } pageName = result.toString(); } mFeatureIds.push_back( qMakePair( feat.id(), pageName ) ); if ( mSortFeatures && sortIdx != -1 ) { mFeatureKeys.insert( feat.id(), feat.attributes().at( sortIdx ) ); } } // sort features, if asked for if ( !mFeatureKeys.isEmpty() ) { FieldSorter sorter( mFeatureKeys, mSortAscending ); qSort( mFeatureIds.begin(), mFeatureIds.end(), sorter ); } emit numberFeaturesChanged( mFeatureIds.size() ); //jump to first feature if currently using an atlas preview //need to do this in case filtering/layer change has altered matching features if ( mComposition->atlasMode() == QgsComposition::PreviewAtlas ) { firstFeature(); } return mFeatureIds.size(); }
static void dumpAttributeVariant(QDebug dbg, const QVariant &var, const QString& indent) { switch (int(var.type())) { case QMetaType::Void: dbg << QString::asprintf("%sEmpty\n", indent.toUtf8().constData()); break; case QMetaType::UChar: dbg << QString::asprintf("%suchar %u\n", indent.toUtf8().constData(), var.toUInt()); break; case QMetaType::UShort: dbg << QString::asprintf("%sushort %u\n", indent.toUtf8().constData(), var.toUInt()); break; case QMetaType::UInt: dbg << QString::asprintf("%suint %u\n", indent.toUtf8().constData(), var.toUInt()); break; case QMetaType::Char: dbg << QString::asprintf("%schar %d\n", indent.toUtf8().constData(), var.toInt()); break; case QMetaType::Short: dbg << QString::asprintf("%sshort %d\n", indent.toUtf8().constData(), var.toInt()); break; case QMetaType::Int: dbg << QString::asprintf("%sint %d\n", indent.toUtf8().constData(), var.toInt()); break; case QMetaType::QString: dbg << QString::asprintf("%sstring %s\n", indent.toUtf8().constData(), var.toString().toUtf8().constData()); break; case QMetaType::Bool: dbg << QString::asprintf("%sbool %d\n", indent.toUtf8().constData(), var.toBool()); break; case QMetaType::QUrl: dbg << QString::asprintf("%surl %s\n", indent.toUtf8().constData(), var.toUrl().toString().toUtf8().constData()); break; case QVariant::UserType: if (var.userType() == qMetaTypeId<QBluetoothUuid>()) { QBluetoothUuid uuid = var.value<QBluetoothUuid>(); switch (uuid.minimumSize()) { case 0: dbg << QString::asprintf("%suuid NULL\n", indent.toUtf8().constData()); break; case 2: dbg << QString::asprintf("%suuid2 %04x\n", indent.toUtf8().constData(), uuid.toUInt16()); break; case 4: dbg << QString::asprintf("%suuid %08x\n", indent.toUtf8().constData(), uuid.toUInt32()); break; case 16: dbg << QString::asprintf("%suuid %s\n", indent.toUtf8().constData(), QByteArray(reinterpret_cast<const char *>(uuid.toUInt128().data), 16).toHex().constData()); break; default: dbg << QString::asprintf("%suuid ???\n", indent.toUtf8().constData()); } } else if (var.userType() == qMetaTypeId<QBluetoothServiceInfo::Sequence>()) { dbg << QString::asprintf("%sSequence\n", indent.toUtf8().constData()); const QBluetoothServiceInfo::Sequence *sequence = static_cast<const QBluetoothServiceInfo::Sequence *>(var.data()); foreach (const QVariant &v, *sequence) dumpAttributeVariant(dbg, v, indent + QLatin1Char('\t')); } else if (var.userType() == qMetaTypeId<QBluetoothServiceInfo::Alternative>()) {
bool TableModelGlobalVariables::setData(QModelIndex const & index, QVariant const & value, int role) { if (role != Qt::EditRole) { return false; } if (!index.isValid()) { return false; } int row = index.row(); if (!(row < globalVariables.size())) { return false; } QPair< QString, QString > & globalVariable_ = globalVariables[row]; switch (index.column()) { case 0 : { if (!value.canConvert(QVariant::String)) { qWarning() << "Variant contains non string value"; return false; } QString name = value.toString(); if (!Settings::getPersistentSettings().symbolExpression.exactMatch(name)) { qWarning() << name + " is not correct symbol name"; return false; } if (Settings::getPersistentSettings().dummySymbolExpression.exactMatch(name)) { qWarning() << "The underscore symbol used as dummy variable name"; return false; } if (Settings::getPersistentSettings().reservedSymbols.contains(name)) { qWarning() << "Symbol " + name + " is reserved"; return false; } for (QPair< QString, QString > const & globalVariable : globalVariables) { if (globalVariable.first == name) { qWarning() << "A duplicates of symbols are not allowed"; return false; } } globalVariable_.first = name; break; } case 1 : { if (!value.canConvert(QVariant::String)) { qWarning() << "Variant contains non string value"; return false; } QString variableValue = value.toString(); if (!variableValue.isEmpty()) { if (!Settings::getPersistentSettings().floatingPointExpression.exactMatch(variableValue)) { qWarning() << "Variant contains string which is nonconvertible to floating-point number"; return false; } } globalVariable_.second = variableValue; break; } default : { return false; } } emit dataChanged(index, index); return true; }
void Config::handleOption(const QString &option, const QVariant &value) { bool boolValue = false; QStringList booleanFlags; booleanFlags << "debug"; booleanFlags << "disk-cache"; booleanFlags << "ignore-ssl-errors"; booleanFlags << "load-images"; booleanFlags << "local-to-remote-url-access"; booleanFlags << "remote-debugger-autorun"; booleanFlags << "web-security"; if (booleanFlags.contains(option)) { if ((value != "true") && (value != "yes") && (value != "false") && (value != "no")) { setUnknownOption(QString("Invalid values for '%1' option.").arg(option)); return; } boolValue = (value == "true") || (value == "yes"); } if (option == "cookies-file") { setCookiesFile(value.toString()); } if (option == "config") { loadJsonFile(value.toString()); } if (option == "debug") { setPrintDebugMessages(boolValue); } if (option == "disk-cache") { setDiskCacheEnabled(boolValue); } if (option == "ignore-ssl-errors") { setIgnoreSslErrors(boolValue); } if (option == "load-images") { setAutoLoadImages(boolValue); } if (option == "local-storage-path") { setOfflineStoragePath(value.toString()); } if (option == "local-storage-quota") { setOfflineStorageDefaultQuota(value.toInt()); } if (option == "local-to-remote-url-access") { setLocalToRemoteUrlAccessEnabled(boolValue); } if (option == "max-disk-cache") { setMaxDiskCacheSize(value.toInt()); } if (option == "output-encoding") { setOutputEncoding(value.toString()); } if (option == "remote-debugger-autorun") { setRemoteDebugAutorun(boolValue); } if (option == "remote-debugger-port") { setDebug(true); setRemoteDebugPort(value.toInt()); } if (option == "proxy") { setProxy(value.toString()); } if (option == "proxy-type") { setProxyType(value.toString()); } if (option == "proxy-auth") { setProxyAuth(value.toString()); } if (option == "script-encoding") { setScriptEncoding(value.toString()); } if (option == "web-security") { setWebSecurityEnabled(boolValue); } if (option == "ssl-protocol") { setSslProtocol(value.toString()); } if (option == "webdriver") { setWebdriver(value.toString()); } if (option == "webdriver-selenium-grid-hub") { setWebdriverSeleniumGridHub(value.toString()); } }
void App::init() { QSettings settings; setWindowIcon(QIcon(":/qlcplus.png")); m_tab = new QTabWidget(this); m_tab->setTabPosition(QTabWidget::South); setCentralWidget(m_tab); QLCFile::checkRaspberry(); QVariant var = settings.value(SETTINGS_GEOMETRY); if (var.isValid() == true) { this->restoreGeometry(var.toByteArray()); } else { /* Application geometry and window state */ QSize size = settings.value("/workspace/size").toSize(); if (size.isValid() == true) resize(size); else { if (QLCFile::isRaspberry()) { QRect geometry = qApp->desktop()->availableGeometry(); if (m_noGui == true) { setGeometry(geometry.width(), geometry.height(), 1, 1); } else { int w = geometry.width(); int h = geometry.height(); if (m_overscan == true) { // if we're on a Raspberry Pi, introduce a 5% margin w = (float)geometry.width() * 0.95; h = (float)geometry.height() * 0.95; } setGeometry((geometry.width() - w) / 2, (geometry.height() - h) / 2, w, h); } } else resize(800, 600); } QVariant state = settings.value("/workspace/state", Qt::WindowNoState); if (state.isValid() == true) setWindowState(Qt::WindowState(state.toInt())); } QVariant dir = settings.value(SETTINGS_WORKINGPATH); if (dir.isValid() == true) m_workingDirectory = QDir(dir.toString()); // The engine object initDoc(); // Main view actions initActions(); // Main tool bar initToolBar(); m_dumpProperties = new DmxDumpFactoryProperties(KUniverseCount); // Create primary views. m_tab->setIconSize(QSize(24, 24)); QWidget* w = new FixtureManager(m_tab, m_doc); m_tab->addTab(w, QIcon(":/fixture.png"), tr("Fixtures")); w = new FunctionManager(m_tab, m_doc); m_tab->addTab(w, QIcon(":/function.png"), tr("Functions")); w = new ShowManager(m_tab, m_doc); m_tab->addTab(w, QIcon(":/show.png"), tr("Shows")); w = new VirtualConsole(m_tab, m_doc); m_tab->addTab(w, QIcon(":/virtualconsole.png"), tr("Virtual Console")); w = new SimpleDesk(m_tab, m_doc); m_tab->addTab(w, QIcon(":/slidermatrix.png"), tr("Simple Desk")); w = new InputOutputManager(m_tab, m_doc); m_tab->addTab(w, QIcon(":/input_output.png"), tr("Inputs/Outputs")); // Listen to blackout changes and toggle m_controlBlackoutAction connect(m_doc->inputOutputMap(), SIGNAL(blackoutChanged(bool)), this, SLOT(slotBlackoutChanged(bool))); // Listen to DMX value changes and update each Fixture values array connect(m_doc->inputOutputMap(), SIGNAL(universesWritten(int, const QByteArray&)), this, SLOT(slotUniversesWritten(int, const QByteArray&))); // Enable/Disable panic button connect(m_doc->masterTimer(), SIGNAL(functionListChanged()), this, SLOT(slotRunningFunctionsChanged())); slotRunningFunctionsChanged(); // Start up in non-modified state m_doc->resetModified(); QString ssDir; #if defined(WIN32) || defined(Q_OS_WIN) /* User's input profile directory on Windows */ LPTSTR home = (LPTSTR) malloc(256 * sizeof(TCHAR)); GetEnvironmentVariable(TEXT("UserProfile"), home, 256); ssDir = QString("%1/%2").arg(QString::fromUtf16(reinterpret_cast<ushort*> (home))) .arg(USERQLCPLUSDIR); free(home); HotPlugMonitor::setWinId(winId()); #else /* User's input profile directory on *NIX systems */ ssDir = QString("%1/%2").arg(getenv("HOME")).arg(USERQLCPLUSDIR); #endif QFile ssFile(ssDir + QDir::separator() + "qlcplusStyle.qss"); if (ssFile.exists() == true) { ssFile.open(QFile::ReadOnly); QString styleSheet = QLatin1String(ssFile.readAll()); this->setStyleSheet(styleSheet); } #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) m_videoProvider = new VideoProvider(m_doc, this); #endif }
// Return contents of form editor (loosely coupled) static inline QString formWindowEditorContents(const QObject *editor) { const QVariant contentV = editor->property("contents"); QTC_ASSERT(contentV.isValid(), return QString()); return contentV.toString(); }
enum SetResponse apOpenItem::set(const ParameterList &pParams) { XDialog::set(pParams); QVariant param; bool valid; param = pParams.value("docType", &valid); if (valid) { if (param.toString() == "creditMemo") { setWindowTitle(windowTitle() + tr(" - Enter Misc. Credit Memo")); _docType->setCurrentIndex(0); _status->setEnabled(false); } else if (param.toString() == "debitMemo") { setWindowTitle(windowTitle() + tr(" - Enter Misc. Debit Memo")); _docType->setCurrentIndex(1); } else if (param.toString() == "voucher") _docType->setCurrentIndex(2); else return UndefinedError; // ToDo - better error return types _docType->setEnabled(FALSE); } param = pParams.value("mode", &valid); XSqlQuery setOpenItem; if (valid) { if (param.toString() == "new") { _mode = cNew; setOpenItem.exec("SELECT fetchAPMemoNumber() AS number;"); if (setOpenItem.first()) { _docNumber->setText(setOpenItem.value("number").toString()); _seqiss = setOpenItem.value("number").toInt(); } _paid->clear(); _buttonBox->button(QDialogButtonBox::Save)->setText(tr("Post")); populateStatus(); } else if (param.toString() == "edit") { _mode = cEdit; _vend->setReadOnly(TRUE); _docDate->setEnabled(FALSE); _dueDate->setEnabled(FALSE); _docType->setEnabled(FALSE); _docNumber->setEnabled(FALSE); _poNumber->setEnabled(FALSE); _journalNumber->setEnabled(FALSE); _terms->setEnabled(FALSE); _notes->setReadOnly(FALSE); _useAltPrepaid->setEnabled(FALSE); _altAccntid->setEnabled(FALSE); } else if (param.toString() == "view") { _mode = cView; _vend->setReadOnly(TRUE); _docDate->setEnabled(FALSE); _dueDate->setEnabled(FALSE); _docType->setEnabled(FALSE); _docNumber->setEnabled(FALSE); _poNumber->setEnabled(FALSE); _journalNumber->setEnabled(FALSE); _amount->setEnabled(FALSE); _terms->setEnabled(FALSE); _terms->setType(XComboBox::Terms); _notes->setReadOnly(TRUE); _useAltPrepaid->setEnabled(FALSE); _altAccntid->setEnabled(FALSE); _status->setEnabled(FALSE); _buttonBox->setStandardButtons(QDialogButtonBox::Close); } } param = pParams.value("vend_id", &valid); if (valid) _vend->setId(param.toInt()); param = pParams.value("apopen_id", &valid); if (valid) { _apopenid = param.toInt(); populate(); } return NoError; }
bool QgsLocatorFiltersModel::setData( const QModelIndex &index, const QVariant &value, int role ) { if ( !index.isValid() || index.parent().isValid() || index.row() < 0 || index.column() < 0 || index.row() >= rowCount( QModelIndex() ) || index.column() >= columnCount( QModelIndex() ) ) return false; switch ( role ) { case Qt::EditRole: { switch ( index.column() ) { case Name: case Active: case Default: return false; case Prefix: { QString prefix = value.toString(); if ( !prefix.isEmpty() ) { mPrefixes.insert( filterForIndex( index ), prefix ); } else { // reset to the native prefix mPrefixes.insert( filterForIndex( index ), filterForIndex( index )->prefix() ); } emit dataChanged( index, index ); return true; } } return false; } case Qt::CheckStateRole: { bool checked = static_cast< Qt::CheckState >( value.toInt() ) == Qt::Checked; switch ( index.column() ) { case Name: case Prefix: return false; case Active: { mEnabledChanges.insert( filterForIndex( index ), checked ); emit dataChanged( index, index ); return true; } case Default: { mDefaultChanges.insert( filterForIndex( index ), checked ); emit dataChanged( index, index ); return true; } } } } return false; }
QDomElement QgsXmlUtils::writeVariant( const QVariant &value, QDomDocument &doc ) { QDomElement element = doc.createElement( QStringLiteral( "Option" ) ); switch ( value.type() ) { case QVariant::Invalid: { element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "invalid" ) ); break; } case QVariant::Map: { QVariantMap map = value.toMap(); for ( auto option = map.constBegin(); option != map.constEnd(); ++option ) { QDomElement optionElement = writeVariant( option.value(), doc ); optionElement.setAttribute( QStringLiteral( "name" ), option.key() ); element.appendChild( optionElement ); element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "Map" ) ); } break; } case QVariant::List: { QVariantList list = value.toList(); const auto constList = list; for ( const QVariant &value : constList ) { QDomElement valueElement = writeVariant( value, doc ); element.appendChild( valueElement ); element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "List" ) ); } break; } case QVariant::StringList: { QStringList list = value.toStringList(); const auto constList = list; for ( const QString &value : constList ) { QDomElement valueElement = writeVariant( value, doc ); element.appendChild( valueElement ); element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "StringList" ) ); } break; } case QVariant::Int: case QVariant::UInt: case QVariant::Bool: case QVariant::Double: case QVariant::LongLong: case QVariant::ULongLong: case QVariant::String: element.setAttribute( QStringLiteral( "type" ), QVariant::typeToName( value.type() ) ); element.setAttribute( QStringLiteral( "value" ), value.toString() ); break; case QVariant::UserType: { if ( value.canConvert< QgsProperty >() ) { element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "QgsProperty" ) ); const QDomElement propertyElem = QgsXmlUtils::writeVariant( value.value< QgsProperty >().toVariant(), doc ); element.appendChild( propertyElem ); break; } else if ( value.canConvert< QgsCoordinateReferenceSystem >() ) { element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "QgsCoordinateReferenceSystem" ) ); const QgsCoordinateReferenceSystem crs = value.value< QgsCoordinateReferenceSystem >(); crs.writeXml( element, doc ); break; } else if ( value.canConvert< QgsGeometry >() ) { element.setAttribute( QStringLiteral( "type" ), QStringLiteral( "QgsGeometry" ) ); const QgsGeometry geom = value.value< QgsGeometry >(); element.setAttribute( QStringLiteral( "value" ), geom.asWkt() ); break; } FALLTHROUGH } default: Q_ASSERT_X( false, "QgsXmlUtils::writeVariant", QStringLiteral( "unsupported variant type %1" ).arg( QVariant::typeToName( value.type() ) ).toLocal8Bit() ); break; } return element; }
void ChatView::evaluateJavaScript(const QString &func, const QVariant ¶m) { evaluateJavaScript(func + LS("(") + param.toString() + LS(");")); }
QStringList splitString(const QVariant &value) { using namespace Help::Constants; return value.toString().split(ListSeparator, QString::SkipEmptyParts); }
QByteArray QgsSvgCache::getImageData( const QString &path ) const { // is it a path to local file? QFile svgFile( path ); if ( svgFile.exists() ) { if ( svgFile.open( QIODevice::ReadOnly ) ) { return svgFile.readAll(); } else { return mMissingSvg; } } // maybe it's a url... if ( !path.contains( "://" ) ) // otherwise short, relative SVG paths might be considered URLs { return mMissingSvg; } QUrl svgUrl( path ); if ( !svgUrl.isValid() ) { return mMissingSvg; } // check whether it's a url pointing to a local file if ( svgUrl.scheme().compare( "file", Qt::CaseInsensitive ) == 0 ) { svgFile.setFileName( svgUrl.toLocalFile() ); if ( svgFile.exists() ) { if ( svgFile.open( QIODevice::ReadOnly ) ) { return svgFile.readAll(); } } // not found... return mMissingSvg; } // the url points to a remote resource, download it! QNetworkReply *reply = nullptr; // The following code blocks until the file is downloaded... // TODO: use signals to get reply finished notification, in this moment // it's executed while rendering. while ( 1 ) { QgsDebugMsg( QString( "get svg: %1" ).arg( svgUrl.toString() ) ); QNetworkRequest request( svgUrl ); request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache ); request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true ); reply = QgsNetworkAccessManager::instance()->get( request ); connect( reply, SIGNAL( downloadProgress( qint64, qint64 ) ), this, SLOT( downloadProgress( qint64, qint64 ) ) ); //emit statusChanged( tr( "Downloading svg." ) ); // wait until the image download finished // TODO: connect to the reply->finished() signal while ( !reply->isFinished() ) { QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents, 500 ); } if ( reply->error() != QNetworkReply::NoError ) { QgsMessageLog::logMessage( tr( "SVG request failed [error: %1 - url: %2]" ).arg( reply->errorString(), reply->url().toString() ), tr( "SVG" ) ); reply->deleteLater(); return QByteArray(); } QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute ); if ( redirect.isNull() ) { // neither network error nor redirection // TODO: cache the image break; } // do a new request to the redirect url svgUrl = redirect.toUrl(); reply->deleteLater(); } QVariant status = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute ); if ( !status.isNull() && status.toInt() >= 400 ) { QVariant phrase = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ); QgsMessageLog::logMessage( tr( "SVG request error [status: %1 - reason phrase: %2]" ).arg( status.toInt() ).arg( phrase.toString() ), tr( "SVG" ) ); reply->deleteLater(); return mMissingSvg; } QString contentType = reply->header( QNetworkRequest::ContentTypeHeader ).toString(); QgsDebugMsg( "contentType: " + contentType ); if ( !contentType.startsWith( "image/svg+xml", Qt::CaseInsensitive ) ) { reply->deleteLater(); return mMissingSvg; } // read the image data QByteArray ba = reply->readAll(); reply->deleteLater(); return ba; }
bool FloatRangeValidator::ValidateInternal(const QVariant &value) { QString validateValue = value.toString(); int pos = 0; return innerValidator.validate(validateValue, pos) == QValidator::Acceptable; }
void readString() { QVariant value = settings->defaultValue("testString"); QCOMPARE(value.toString(), QStringLiteral("howdy?")); }
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 == 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; } }
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(); } }
bool GConfLayer::getValue(Handle handle, const QString &subPath, QVariant *data) { if (handle != InvalidHandle && !gConfHandle(handle)) return false; QString path(subPath); while (path.endsWith(QLatin1Char('/'))) path.chop(1); if (handle != InvalidHandle) { while (path.startsWith(QLatin1Char('/'))) path = path.mid(1); } int index = path.lastIndexOf(QLatin1Char('/'), -1); bool createdHandle = false; QString value; if (index == -1) { value = path; } else { // want a value that is in a sub path under handle value = path.mid(index + 1); path.truncate(index); if (path.isEmpty()) path.append(QLatin1Char('/')); handle = getItem(handle, path); createdHandle = true; } GConfHandle *sh = gConfHandle(handle); if (!sh) return false; QString fullPath(sh->path); if (fullPath != QLatin1String("/") && !value.isEmpty()) fullPath.append(QLatin1Char('/')); fullPath.append(value); GConfItem gconfItem(fullPath); QVariant readValue = gconfItem.value(); switch (readValue.type()) { case QVariant::Invalid: case QVariant::Bool: case QVariant::Int: case QVariant::Double: case QVariant::StringList: case QVariant::List: *data = readValue; break; case QVariant::String: { QString readString = readValue.toString(); QDataStream readStream(QByteArray::fromBase64(readString.toLatin1())); QVariant serializedValue; readStream >> serializedValue; if (serializedValue.isValid()) *data = serializedValue; else *data = readValue; break; } default: break; } if (createdHandle) doRemoveHandle(handle); return data->isValid(); }