void SimpleText::draw(QPainter* p) const { p->setFont(textStyle().fontPx(spatium())); p->setBrush(Qt::NoBrush); p->setPen(textColor()); int rows = _layout.size(); if (_editMode && _cursor.hasSelection()) { int r1 = _cursor.selectLine; int r2 = _cursor.line; int c1 = _cursor.selectColumn; int c2 = _cursor.column; if (r1 > r2) { qSwap(r1, r2); qSwap(c1, c2); } else if (r1 == r2) { if (c1 > c2) qSwap(c1, c2); } for (int row = 0; row < rows; ++row) { const TLine& t = _layout.at(row); p->drawText(t.pos, t.text); if (row >= r1 && row <= r2) { QBrush bg(QColor("steelblue")); QFontMetricsF fm(_textStyle.fontPx(spatium())); QRectF br; if (row == r1 && r1 == r2) { QString left = t.text.left(c1); QString mid = t.text.mid(c1, c2 - c1); QString right = t.text.mid(c2); QPointF r (fm.width(left), 0.0); br = fm.boundingRect(mid).translated(t.pos + r); br.setWidth(fm.width(mid)); } else if (row == r1) { QString left = t.text.left(c1); QString right = t.text.mid(c1); QPointF r (fm.width(left), 0.0); br = fm.boundingRect(right).translated(t.pos + r); br.setWidth(fm.width(right)); } else if (row == r2) { QString left = t.text.left(c2); br = fm.boundingRect(left).translated(t.pos); br.setWidth(fm.width(left)); } else { br = fm.boundingRect(t.text).translated(t.pos); br.setWidth(fm.width(t.text)); } drawSelection(p, br); } } } else { for (int row = 0; row < rows; ++row) { const TLine& t = _layout.at(row); p->drawText(t.pos, t.text); } } if (_editMode) { p->setBrush(QColor("steelblue")); p->drawRect(cursorRect()); } }
Selection::GrabZone Selection::grabZone(QPointF pagePos, qreal zoom) { GrabZone grabZone = GrabZone::None; QRectF bRect = m_selectionPolygon.boundingRect(); QRectF moveRect = bRect; qreal scaled_ad = m_ad / zoom; QRectF topRect = bRect; topRect.setTop(topRect.top() - scaled_ad); topRect.setHeight(scaled_ad); QRectF bottomRect = bRect; bottomRect.setTop(bottomRect.bottom()); bottomRect.setHeight(scaled_ad); QRectF leftRect = bRect; leftRect.setLeft(leftRect.left() - scaled_ad); leftRect.setWidth(scaled_ad); QRectF rightRect = bRect; rightRect.setLeft(rightRect.right()); rightRect.setWidth(scaled_ad); QRectF topLeftRect = bRect; topLeftRect.setLeft(topLeftRect.left() - scaled_ad); topLeftRect.setTop(topLeftRect.top() - scaled_ad); topLeftRect.setWidth(scaled_ad); topLeftRect.setHeight(scaled_ad); QRectF topRightRect = bRect; topRightRect.setLeft(topRightRect.right()); topRightRect.setTop(topRightRect.top() - scaled_ad); topRightRect.setWidth(scaled_ad); topRightRect.setHeight(scaled_ad); QRectF bottomLeftRect = bRect; bottomLeftRect.setLeft(bottomLeftRect.left() - scaled_ad); bottomLeftRect.setTop(bottomLeftRect.bottom()); bottomLeftRect.setWidth(scaled_ad); bottomLeftRect.setHeight(scaled_ad); QRectF bottomRightRect = bRect; bottomRightRect.setLeft(bottomRightRect.right()); bottomRightRect.setTop(bottomRightRect.bottom()); bottomRightRect.setWidth(scaled_ad); bottomRightRect.setHeight(scaled_ad); QRectF rotateRect = bRect; rotateRect.setTop(rotateRect.top() - 1.0 * scaled_ad - (m_rotateRectCenter + m_rotateRectRadius) / zoom); rotateRect.setLeft(rotateRect.center().x() - m_rotateRectRadius / zoom); rotateRect.setWidth(2.0 * m_rotateRectRadius / zoom); rotateRect.setHeight(2.0 * m_rotateRectRadius / zoom); if (moveRect.contains(pagePos)) { grabZone = GrabZone::Move; } else if (topRect.contains(pagePos)) { grabZone = GrabZone::Top; } else if (bottomRect.contains(pagePos)) { grabZone = GrabZone::Bottom; } else if (leftRect.contains(pagePos)) { grabZone = GrabZone::Left; } else if (rightRect.contains(pagePos)) { grabZone = GrabZone::Right; } else if (topLeftRect.contains(pagePos)) { grabZone = GrabZone::TopLeft; } else if (topRightRect.contains(pagePos)) { grabZone = GrabZone::TopRight; } else if (bottomLeftRect.contains(pagePos)) { grabZone = GrabZone::BottomLeft; } else if (bottomRightRect.contains(pagePos)) { grabZone = GrabZone::BottomRight; } else if (rotateRect.contains(pagePos)) { grabZone = GrabZone::Rotate; } qInfo() << bRect; qInfo() << rotateRect; return grabZone; }
QRectF QgsComposerItem::evalItemRect( const QRectF &newRect, const bool resizeOnly, const QgsExpressionContext* context ) { QRectF result = newRect; //TODO QGIS 3.0 //maintain pre 2.12 API. remove when API break allowed QScopedPointer< QgsExpressionContext > scopedContext; const QgsExpressionContext* evalContext = context; if ( !evalContext ) { scopedContext.reset( createExpressionContext() ); evalContext = scopedContext.data(); } //data defined position or size set? if so, update rect with data defined values QVariant exprVal; //evaulate width and height first, since they may affect position if non-top-left reference point set if ( dataDefinedEvaluate( QgsComposerObject::ItemWidth, exprVal, *evalContext ) ) { bool ok; double width = exprVal.toDouble( &ok ); QgsDebugMsg( QString( "exprVal Width:%1" ).arg( width ) ); if ( ok && !exprVal.isNull() ) { result.setWidth( width ); } } if ( dataDefinedEvaluate( QgsComposerObject::ItemHeight, exprVal, *evalContext ) ) { bool ok; double height = exprVal.toDouble( &ok ); QgsDebugMsg( QString( "exprVal Height:%1" ).arg( height ) ); if ( ok && !exprVal.isNull() ) { result.setHeight( height ); } } double x = result.left(); //initially adjust for position mode to get x coordinate if ( !resizeOnly ) { //adjust x-coordinate if placement is not done to a left point if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x += newRect.width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x += newRect.width(); } } else { if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x += rect().width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x += rect().width(); } } if ( dataDefinedEvaluate( QgsComposerObject::PositionX, exprVal, *evalContext ) ) { bool ok; double positionX = exprVal.toDouble( &ok ); QgsDebugMsg( QString( "exprVal Position X:%1" ).arg( positionX ) ); if ( ok && !exprVal.isNull() ) { x = positionX; } } double y = result.top(); //initially adjust for position mode to get y coordinate if ( !resizeOnly ) { //adjust y-coordinate if placement is not done to an upper point if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y += newRect.height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y += newRect.height(); } } else { if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y += rect().height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y += rect().height(); } } if ( dataDefinedEvaluate( QgsComposerObject::PositionY, exprVal, *evalContext ) ) { bool ok; double positionY = exprVal.toDouble( &ok ); QgsDebugMsg( QString( "exprVal Position Y:%1" ).arg( positionY ) ); if ( ok && !exprVal.isNull() ) { y = positionY; } } //adjust x-coordinate if placement is not done to a left point if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x -= result.width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x -= result.width(); } //adjust y-coordinate if placement is not done to an upper point if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y -= result.height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y -= result.height(); } result.moveLeft( x ); result.moveTop( y ); return result; }
/*! \brief Draw the raster data \param painter Painter \param xMap X-Scale Map \param yMap Y-Scale Map \param canvasRect Contents rectangle of the plot canvas */ void QwtPlotRasterItem::draw( QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &canvasRect ) const { if ( canvasRect.isEmpty() || d_data->alpha == 0 ) return; const bool doCache = qwtUseCache( d_data->cache.policy, painter ); const QwtInterval xInterval = interval( Qt::XAxis ); const QwtInterval yInterval = interval( Qt::YAxis ); /* Scaling an image always results in a loss of precision/quality. So we always render the image in paint device resolution. */ QwtScaleMap xxMap, yyMap; qwtTransformMaps( painter->transform(), xMap, yMap, xxMap, yyMap ); QRectF paintRect = painter->transform().mapRect( canvasRect ); QRectF area = QwtScaleMap::invTransform( xxMap, yyMap, paintRect ); const QRectF br = boundingRect(); if ( br.isValid() && !br.contains( area ) ) { area &= br; if ( !area.isValid() ) return; paintRect = QwtScaleMap::transform( xxMap, yyMap, area ); } QRectF imageRect; QImage image; QRectF pixelRect = pixelHint(area); if ( !pixelRect.isEmpty() ) { // one pixel of the target device in plot coordinates const double dx = qAbs( xxMap.invTransform( 1 ) - xxMap.invTransform( 0 ) ); const double dy = qAbs( yyMap.invTransform( 1 ) - yyMap.invTransform( 0 ) ); if ( dx > pixelRect.width() && dy > pixelRect.height() ) { /* When the resolution of the data pixels is higher than the resolution of the target device we render in target device resolution. */ pixelRect = QRectF(); } else { /* If only one dimension is of the data pixel is higher we expand the pixel rect to the resolution of the target device. */ if ( dx > pixelRect.width() ) pixelRect.setWidth( dx ); if ( dy > pixelRect.height() ) pixelRect.setHeight( dy ); } } if ( pixelRect.isEmpty() ) { if ( QwtPainter::roundingAlignment( painter ) ) { // we want to have maps, where the boundaries of // the aligned paint rectangle exactly match the area paintRect = qwtAlignRect(paintRect); qwtAdjustMaps(xxMap, yyMap, area, paintRect); } // When we have no information about position and size of // data pixels we render in resolution of the paint device. image = compose(xxMap, yyMap, area, paintRect, paintRect.size().toSize(), doCache); if ( image.isNull() ) return; // Remove pixels at the boundaries, when explicitly // excluded in the intervals imageRect = qwtStripRect(paintRect, area, xxMap, yyMap, xInterval, yInterval); if ( imageRect != paintRect ) { const QRect r( qRound( imageRect.x() - paintRect.x()), qRound( imageRect.y() - paintRect.y() ), qRound( imageRect.width() ), qRound( imageRect.height() ) ); image = image.copy(r); } } else { if ( QwtPainter::roundingAlignment( painter ) ) paintRect = qwtAlignRect(paintRect); // align the area to the data pixels QRectF imageArea = qwtExpandToPixels(area, pixelRect); if ( imageArea.right() == xInterval.maxValue() && !( xInterval.borderFlags() & QwtInterval::ExcludeMaximum ) ) { imageArea.adjust(0, 0, pixelRect.width(), 0); } if ( imageArea.bottom() == yInterval.maxValue() && !( yInterval.borderFlags() & QwtInterval::ExcludeMaximum ) ) { imageArea.adjust(0, 0, 0, pixelRect.height() ); } QSize imageSize; imageSize.setWidth( qRound( imageArea.width() / pixelRect.width() ) ); imageSize.setHeight( qRound( imageArea.height() / pixelRect.height() ) ); image = compose(xxMap, yyMap, imageArea, paintRect, imageSize, doCache ); if ( image.isNull() ) return; imageRect = qwtStripRect(paintRect, area, xxMap, yyMap, xInterval, yInterval); if ( ( image.width() > 1 || image.height() > 1 ) && testPaintAttribute( PaintInDeviceResolution ) ) { // Because of rounding errors the pixels // need to be expanded manually to rectangles of // different sizes image = qwtExpandImage(image, xxMap, yyMap, imageArea, area, paintRect, xInterval, yInterval ); } } painter->save(); painter->setWorldTransform( QTransform() ); QwtPainter::drawImage( painter, imageRect, image ); painter->restore(); }
LaneSettings::LaneSettings(ProjectSettings *projectSettings, SettingsElement *parentSettingsElement, Lane *lane) : SettingsElement(projectSettings, parentSettingsElement, lane) , ui(new Ui::LaneSettings) , lane_(lane) , init_(false) , roadSystemItemPolyGraph_(NULL) , insertWidthSectionHandle_(NULL) , lswItem_(NULL) { ui->setupUi(this); activateWidthGroupBox(false); activateInsertGroupBox(false); connect(ui->insertPushButton, SIGNAL(clicked(bool)), this, SLOT(activateInsertGroupBox(bool))); connect(ui->editPushButton, SIGNAL(clicked(bool)), this, SLOT(activateWidthGroupBox(bool))); // List // // QStringList typeNames; typeNames << Lane::parseLaneTypeBack(Lane::LT_NONE) << Lane::parseLaneTypeBack(Lane::LT_DRIVING) << Lane::parseLaneTypeBack(Lane::LT_STOP) << Lane::parseLaneTypeBack(Lane::LT_SHOULDER) << Lane::parseLaneTypeBack(Lane::LT_BIKING) << Lane::parseLaneTypeBack(Lane::LT_SIDEWALK) << Lane::parseLaneTypeBack(Lane::LT_BORDER) << Lane::parseLaneTypeBack(Lane::LT_RESTRICTED) << Lane::parseLaneTypeBack(Lane::LT_PARKING) << Lane::parseLaneTypeBack(Lane::LT_MWYENTRY) << Lane::parseLaneTypeBack(Lane::LT_MWYEXIT) << Lane::parseLaneTypeBack(Lane::LT_SPECIAL1) << Lane::parseLaneTypeBack(Lane::LT_SPECIAL2) << Lane::parseLaneTypeBack(Lane::LT_SPECIAL3); ui->typeBox->addItems(typeNames); /*heightGraph_ = new ProfileGraph(projectSettings->getProjectWidget(), projectSettings->getProjectData()); heightGraph_->setParent(ui->widthGroup); ui->horizontalLayout_3->insertWidget(0,heightGraph_); //heightGraph_->getView()->setDragMode(QGraphicsView::ScrollHandDrag); //QGraphicsScene* pScene = new NoDeselectScene(this); //heightGraph_->getView()->setScene(pScene); heightGraph_->getScene()->doDeselect(false);// we don't want to deselect ourselves if we click on the background, otherwise we delete ourselves--> chrash and it would not be practical anyway */ heightGraph_ = projectSettings->getProjectWidget()->getHeightGraph(); laneEditor_ = dynamic_cast<LaneEditor *>(projectSettings->getProjectWidget()->getProjectEditor()); if (!laneEditor_) { return; // another editor is active } roadSystemItemPolyGraph_ = new LaneWidthRoadSystemItem(heightGraph_, projectSettings->getProjectData()->getRoadSystem()); heightGraph_->getScene()->addItem(roadSystemItemPolyGraph_); // Section Handle // // //insertWidthSectionHandle_ = new SectionHandle(roadSystemItemPolyGraph_); //insertWidthSectionHandle_->hide(); roadSystemItemPolyGraph_->setSettings(this); roadSystemItemPolyGraph_->setAcceptHoverEvents(true); // Activate Road in ProfileGraph // // lswItem_ = new LaneSectionWidthItem(roadSystemItemPolyGraph_, lane_); //selectedElevationRoadItems_.insert(road, roadItem); // Fit View // // QRectF boundingBox = lswItem_->boundingRect(); if (boundingBox.width() < 15.0) { boundingBox.setWidth(15.0); } if (boundingBox.height() < 10.0) { boundingBox.setHeight(10.0); } heightGraph_->getView()->fitInView(boundingBox); heightGraph_->getView()->zoomOut(Qt::Horizontal | Qt::Vertical); //ui->horizontalLayout_3->insertWidget(0,heightGraph_); //heightGraph_->show(); // Initial Values // // updateId(); updateType(); updateLevel(); updatePredecessor(); updateSuccessor(); updateWidth(); // Done // // init_ = true; }
/* Calculates the rects for the popup text and background. Does nothing if the rect is the same as the last time it was called. */ void HbIndexFeedbackPrivate::calculatePopupRects() { Q_Q( HbIndexFeedback ); if (!mItemView) { return; } QRectF contentRect = mItemView->mapToItem(q, mItemView->rect()).boundingRect(); HbScrollBar *verticalScrollBar = mItemView->verticalScrollBar(); HbScrollBar *horizontalScrollBar = mItemView->horizontalScrollBar(); if (verticalScrollBar->isInteractive()) { contentRect.setWidth( contentRect.width() - verticalScrollBar->rect().width() ); if (HbApplication::layoutDirection() == Qt::RightToLeft) { contentRect.setLeft( contentRect.left() + verticalScrollBar->rect().width() ); } } if (horizontalScrollBar->isInteractive()) { contentRect.setHeight( contentRect.height() - horizontalScrollBar->rect().height() ); } if (contentRect == mItemViewContentsRect) { return; } qreal margin = 0; q->style()->parameter(QLatin1String("hb-param-margin-gene-popup"), margin); QSizeF backgroundSize; QSizeF textSize; switch (mIndexFeedbackPolicy) { case HbIndexFeedback::IndexFeedbackSingleCharacter: case HbIndexFeedback::IndexFeedbackThreeCharacter: { textSize.setHeight( textHeight() ); textSize.setWidth ( textWidth() ); backgroundSize.setHeight( textSize.height() + 2 * margin ); backgroundSize.setWidth ( textSize.width() + 2 * margin ); mPopupBackgroundRect.setLeft( contentRect.left() + (contentRect.width() - backgroundSize.width()) / 2.0 ); mPopupBackgroundRect.setTop ( contentRect.top() + (contentRect.height() - backgroundSize.height()) / 2.0 ); mPopupTextRect.setLeft( mPopupBackgroundRect.left() + margin ); mPopupTextRect.setTop ( mPopupBackgroundRect.top() + margin ); mPopupBackgroundRect.setSize(backgroundSize); mPopupTextRect.setSize(textSize); } break; case HbIndexFeedback::IndexFeedbackString: { textSize.setHeight( textHeight() ); backgroundSize.setHeight( textSize.height() + 2 * margin ); backgroundSize.setWidth( contentRect.width() - 2 * mStringOffset ); textSize.setWidth( backgroundSize.width() - 2 * margin ); mPopupBackgroundRect.setLeft( contentRect.left() + mStringOffset ); mPopupBackgroundRect.setTop( contentRect.top() + (contentRect.height() - backgroundSize.height()) / 2.0 ); mPopupTextRect.setLeft( mPopupBackgroundRect.left() + margin ); mPopupTextRect.setTop ( mPopupBackgroundRect.top() + margin ); mPopupBackgroundRect.setSize(backgroundSize); mPopupTextRect.setSize(textSize); } break; case HbIndexFeedback::IndexFeedbackNone: { mPopupTextRect = QRectF(); mPopupBackgroundRect = QRectF(); } break; } }
void QcMultiSlider::paintEvent( QPaintEvent *e ) { using namespace QtCollider::Style; using QtCollider::Style::Ellipse; using QtCollider::Style::RoundRect; Q_UNUSED(e); QPainter p(this); p.setRenderHint( QPainter::Antialiasing, true ); RoundRect frame(rect(), 2); drawSunken( &p, palette(), frame, background(), hasFocus() ? focusColor() : QColor() ); if( !_values.count() ) return; p.setRenderHint( QPainter::Antialiasing, false ); bool horiz = ort == Qt::Horizontal; QRect bounds( contentsRect() ); p.setClipRect( bounds ); if( horiz ) { p.translate( bounds.topLeft() ); p.rotate(90); p.scale(1.0, -1.0); bounds.setSize( QSize( bounds.height(), bounds.width() ) ); } else { p.translate( bounds.left(), bounds.top() + bounds.height() ); p.scale(1.0, -1.0); } int count = _values.count() - startIndex; qreal spacing, width, yscale; spacing = elastic ? (qreal) bounds.width() / count : thumbSize.width() + gap; width = elastic ? qMin( spacing, (qreal) thumbSize.width() ) : thumbSize.width(); yscale = bounds.height(); if( !isFilled ) yscale -= thumbSize.height(); const QColor & fillClr = fillColor(); // selection if( highlight ) { int i = _currentIndex - startIndex; int c = qMin( count - i, _selectionSize ); if(c) { QRect r; r.setHeight( bounds.height() ); r.setWidth( c * spacing ); r.moveLeft( i * spacing ); QColor hlColor = fillClr; hlColor.setAlpha( 70 ); p.fillRect( r, hlColor ); } } QPen pen; pen.setColor(strokeColor()); pen.setWidth(0); p.setPen(pen); // lines if( drawLines ) { bool fill = isFilled & !drawRects; p.save(); p.setRenderHint( QPainter::Antialiasing, true ); p.translate( spacing * 0.5, isFilled ? 0.0 : thumbSize.height() * 0.5 ); p.scale( 1.0, (qreal) yscale ); if( fill ) p.setBrush( fillClr ); QPainterPath path; // value line path.moveTo( 0, _values[startIndex] ); for( int i = 1; i < count; ++i ) path.lineTo( (qreal) i * spacing, _values[i + startIndex] ); // reference line int refcount = _ref.count() - startIndex; if( refcount > 0 || fill ) { qreal x, y; int i = count - 1; x = i * spacing; y = i < refcount ? _ref[i + startIndex] : 0.f; if( fill ) path.lineTo(x, y); else path.moveTo(x, y); while( --i >= 0 ) { x = i * spacing; y = i < refcount ? _ref[i + startIndex] : 0.f; path.lineTo(x, y); } if( fill ) path.closeSubpath(); } p.drawPath( path ); p.restore(); } // rects if( drawRects ) { p.setRenderHint( QPainter::Antialiasing, false ); p.translate( (spacing - width) * 0.5, 0 ); p.setBrush( fillClr ); QRectF r; r.setWidth( width ); if( isFilled ) { int refcount = _ref.count() - startIndex; for( int i = 0; i < count; ++i ) { int ref = (i < refcount ? _ref[i + startIndex] : 0.f) * yscale; int val = _values[i + startIndex] * yscale; r.moveLeft( i * spacing ); r.moveTop( ref ); r.setHeight( val - ref ); if(horiz) p.drawRect(r.normalized().adjusted(0,0,-1,-1)); else p.drawRect(r.normalized().adjusted(0,1,-1,0)); } } else { r.setHeight( thumbSize.height() ); for( int i = 0; i < count; ++i ) { r.moveLeft( i * spacing ); r.moveTop( _values[i + startIndex] * yscale ); if(horiz) p.drawRect(r.adjusted(0,0,-1,-1)); else p.drawRect(r.adjusted(0,1,-1,0)); } } } }
void GridFitting::paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Axis t(0, ylabel->getNpoints(), 0, xlabel->getNpoints()); axis = t; if (!cw) { cw = widget->rect().width(); } if (!ch) { ch = widget->rect().height(); } painter->setFont(*textFont); painter->fillRect(widget->rect(), background); double w1 = 0, h1 = 0; offset = 30; w1 = offset; if (widget->rect().width() != w) { if (w) { rW = (double) (cw / widget->rect().width()); } else { rW = 1; } } if (widget->rect().height() != h) { if (h) { rH = (double) (ch / widget->rect().height()); } else { rH = 1; } } w = widget->rect().width(); h = widget->rect().height(); h1 = h - offset; painter->drawLine(QLineF(QPointF(0, h1), QPointF(w, h1))); painter->drawLine(QLineF(QPointF(offset, 0), QPointF(offset, h))); w1 = w - offset; h1 = h - offset; int k = 1, k1 = 1; Xintervalsw = w1 / axis.x; double stepx =rW * sX*Xintervalsw; double ticksw = tX*stepx; for (double i = 0; i < w; i += Xintervalsw) { QLineF a; if (i >= k * (ticksw)) { a.setPoints(QPointF(offset + i, h1), QPointF(offset + i, h1 - offset / 5)); QRectF text; text.setX(offset + i - ticksw / 2); text.setY(h1); text.setWidth(ticksw); text.setHeight(20); QTextOption fmt(Qt::AlignTop | Qt::AlignCenter); double t = i / Xintervalsw; painter->drawText(text, QString::number(xlabel->getElement(t-1), 10, 2), fmt); k++; k1++; painter->drawLine(a); } else if (i >= k1 * stepx) { a.setPoints(QPointF(i + offset, h1), QPointF(i + offset, h1 - offset / 10)); painter->drawLine(a); k1++; } } k = 1; k1 = 1; Yintervalsh = h1 / axis.y; ZeroPoint = axis.Hy*Yintervalsh; double stepy = rH * sY*Yintervalsh; double ticksh = tY*stepy; for (double i = 0,j=0; i < h1; i += Yintervalsh,j++) { QLineF a; if (i >= (k * ticksh)) { a.setPoints(QPointF(offset, i), QPointF(offset + offset / 5, i)); QRectF text; text.setX(0); text.setY(i - ticksh / 2); text.setWidth(offset); QTextOption fmt(Qt::AlignHCenter | Qt::AlignCenter); text.setHeight(ticksh); QString str = QString::number(ylabel->getElement(i / Yintervalsh-1), 10, 2); painter->drawText(text, str, fmt); k++; k1++; painter->drawLine(a); } else if (i >= k1 * stepy) { a.setPoints(QPointF(offset, i), QPointF(offset + offset / 10, i)); painter->drawLine(a); k1++; } } if (isGridOn()) { painter->setPen(gridpen); k = 1; for (float i = 0; i < axis.y; i++) { QLineF a; if (i >= k * sY * tY) { a.setPoints(QPointF(offset, i * Yintervalsh), QPointF(w, i * Yintervalsh)); painter->drawLine(a); k++; } } k = 1; for (double i = 0; i < w; i += Xintervalsw) { QLineF a; if (i >= k * ticksw) { a.setPoints(QPointF(offset + i, 0), QPointF(offset + i, h1)); painter->drawLine(a); k++; } } } }
void QgsComposerPicture::setSceneRect( const QRectF& rectangle ) { QSizeF currentPictureSize = pictureSize(); if ( mResizeMode == QgsComposerPicture::Clip ) { QgsComposerItem::setSceneRect( rectangle ); mPictureWidth = rectangle.width(); mPictureHeight = rectangle.height(); } else { QRectF newRect = rectangle; if ( mResizeMode == ZoomResizeFrame && !rect().isEmpty() && !( currentPictureSize.isEmpty() ) ) { QSizeF targetImageSize; if ( qgsDoubleNear( mPictureRotation, 0.0 ) ) { targetImageSize = currentPictureSize; } else { //calculate aspect ratio of bounds of rotated image QTransform tr; tr.rotate( mPictureRotation ); QRectF rotatedBounds = tr.mapRect( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ) ); targetImageSize = QSizeF( rotatedBounds.width(), rotatedBounds.height() ); } //if height has changed more than width, then fix width and set height correspondingly //else, do the opposite if ( qAbs( rect().width() - rectangle.width() ) < qAbs( rect().height() - rectangle.height() ) ) { newRect.setHeight( targetImageSize.height() * newRect.width() / targetImageSize.width() ); } else { newRect.setWidth( targetImageSize.width() * newRect.height() / targetImageSize.height() ); } } else if ( mResizeMode == FrameToImageSize ) { if ( !( currentPictureSize.isEmpty() ) ) { newRect.setWidth( currentPictureSize.width() * 25.4 / mComposition->printResolution() ); newRect.setHeight( currentPictureSize.height() * 25.4 / mComposition->printResolution() ); } } //find largest scaling of picture with this rotation which fits in item if ( mResizeMode == Zoom || mResizeMode == ZoomResizeFrame ) { QRectF rotatedImageRect = QgsComposerUtils::largestRotatedRectWithinBounds( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ), newRect, mPictureRotation ); mPictureWidth = rotatedImageRect.width(); mPictureHeight = rotatedImageRect.height(); } else { mPictureWidth = newRect.width(); mPictureHeight = newRect.height(); } QgsComposerItem::setSceneRect( newRect ); emit itemChanged(); } if ( mMode == SVG && !mLoadingSvg ) { mLoadingSvg = true; refreshPicture(); mLoadingSvg = false; } }
QRectF QgsComposerItem::evalItemRect( const QRectF &newRect, const bool resizeOnly, const QgsExpressionContext *context ) { QRectF result = newRect; //TODO QGIS 3.0 //maintain pre 2.12 API. remove when API break allowed QgsExpressionContext scopedContext = createExpressionContext(); const QgsExpressionContext *evalContext = context ? context : &scopedContext; //data defined position or size set? if so, update rect with data defined values bool ok = false; double ddWidth = mDataDefinedProperties.valueAsDouble( QgsComposerObject::ItemWidth, *evalContext, 0, &ok ); //evaulate width and height first, since they may affect position if non-top-left reference point set if ( ok ) { result.setWidth( ddWidth ); } double ddHeight = mDataDefinedProperties.valueAsDouble( QgsComposerObject::ItemHeight, *evalContext, 0, &ok ); if ( ok ) { result.setHeight( ddHeight ); } double x = result.left(); //initially adjust for position mode to get x coordinate if ( !resizeOnly ) { //adjust x-coordinate if placement is not done to a left point if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x += newRect.width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x += newRect.width(); } } else { if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x += rect().width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x += rect().width(); } } double ddPosX = mDataDefinedProperties.valueAsDouble( QgsComposerObject::PositionX, *evalContext, 0.0, &ok ); if ( ok ) { x = ddPosX; } double y = result.top(); //initially adjust for position mode to get y coordinate if ( !resizeOnly ) { //adjust y-coordinate if placement is not done to an upper point if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y += newRect.height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y += newRect.height(); } } else { if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y += rect().height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y += rect().height(); } } double ddPosY = mDataDefinedProperties.valueAsDouble( QgsComposerObject::PositionY, *evalContext, 0, &ok ); if ( ok ) { y = ddPosY; } //adjust x-coordinate if placement is not done to a left point if ( mLastUsedPositionMode == UpperMiddle || mLastUsedPositionMode == Middle || mLastUsedPositionMode == LowerMiddle ) { x -= result.width() / 2.0; } else if ( mLastUsedPositionMode == UpperRight || mLastUsedPositionMode == MiddleRight || mLastUsedPositionMode == LowerRight ) { x -= result.width(); } //adjust y-coordinate if placement is not done to an upper point if ( mLastUsedPositionMode == MiddleLeft || mLastUsedPositionMode == Middle || mLastUsedPositionMode == MiddleRight ) { y -= result.height() / 2.0; } else if ( mLastUsedPositionMode == LowerLeft || mLastUsedPositionMode == LowerMiddle || mLastUsedPositionMode == LowerRight ) { y -= result.height(); } result.moveLeft( x ); result.moveTop( y ); return result; }
void GraphAggRenderer::render(QImage *image1, QRectF clip, agg::trans_affine *t) { agg::trans_affine transform = *t; QImage &image = *image1; agg::rendering_buffer rbuf(image.bits(), image.width(), image.height(), image.width() * 4); agg::pixfmt_bgra32 pixf(rbuf); ren_base ren(pixf); renderer_solid r(ren); ren.clear(agg::rgba(1, 1, 1)); scanline_type sl; agg::rasterizer_scanline_aa<> ras; clip.setX(-500); clip.setY(-500); clip.setWidth(1000); clip.setHeight(1000); qDebug() << "clip: box " << clip; agg::path_storage clip_ps; clip_ps.move_to(clip.x(), clip.y()); clip_ps.line_to(clip.x() + clip.width(), clip.y()); clip_ps.line_to(clip.x() + clip.width(), clip.y() + clip.height()); clip_ps.line_to(clip.x(), clip.y() + clip.height()); //clip_ps.line_to(clip.x(), clip.y()); clip_ps.close_polygon(); agg::path_storage &ps = m_data->ps; for (unsigned i = 0; i < m_data->as.size(); ++i) { const path_attributes &attr = m_data->as[i]; if (attr.fill_flag) { //qDebug() << "++attr.fill_flag"; ras.reset(); agg::conv_contour<agg::path_storage> cc(ps); agg::conv_transform < agg::conv_contour < agg::path_storage > > ct(cc, transform); agg::conv_gpc< agg::conv_transform < agg::conv_contour < agg::path_storage > >, agg::path_storage> gpc(ct, clip_ps); gpc.operation(agg::gpc_and); //ras.add_path(ct, attr.index); ras.add_path(gpc, attr.index); r.color(attr.fill_color); agg::render_scanlines(ras, sl, r); } else if (attr.stroke_flag) { ras.reset(); typedef conv_curve<path_storage> curved; typedef conv_stroke<curved> curved_stroked; typedef conv_transform<curved_stroked> curved_stroked_trans; agg::conv_stroke<agg::path_storage> pg(ps); agg::conv_transform< agg::conv_stroke < agg::path_storage > > ct(pg, transform); agg::conv_gpc<agg::path_storage, agg::path_storage> gpc(clip_ps, ps); /* agg::conv_gpc< agg::conv_transform < agg::conv_stroke < agg::path_storage > >, agg::path_storage> gpc(ct, clip_ps); */ gpc.operation(agg::gpc_or); //gpc.operation(agg::gpc_and); qDebug() << attr.index; pg.width(attr.stroke_width); //ras.add_path(ct, attr.index); //ras.add_path(gpc, attr.index); ras.reset(); gpc.rewind(attr.index); double x; double y; unsigned cmd; while(!agg::is_stop(cmd = gpc.vertex(&x, &y))) { ras.add_vertex(x, y, cmd); qDebug() << "++"; } //ras.reset(); //ras.add_path(clip_ps); //ras.add_path(ps, attr.index); //ras.reset(); //ras.add_path(clip_ps); r.color(attr.stroke_color); agg::render_scanlines(ras, sl, r); } } }
void KUnitItem::slotMouseMove(QGraphicsSceneMouseEvent *event) { if (myMode == MouseMode_RESIZE) { QPointF curPoint(event->scenePos()); QPointF curPointItem = this->mapFromScene(curPoint); bool flagx = lastPoint.x() > oppositePos.x(); bool flagx1 = curPointItem.x() > oppositePos.x(); bool flagy = lastPoint.y() > oppositePos.y(); bool flagy1 = curPointItem.y() > oppositePos.y(); qreal dist = 0; QRectF rectf; rectf.setRect(m_frame.x() , m_frame.y() , m_frame.width() , m_frame.height()); KResizeFocus::PosInHost pos = curResizeFocus->getInHost(); if (pos == KResizeFocus::NORTH_MIDDLE) { QPointF br = dashRect->rect().bottomRight(); dist = Util::GetPointDistLine(oppositePos,br,curPointItem); if (dist < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } dist = 20; } rectf.setY(curPointItem.y()); rectf.setHeight(dist); } else if(pos == KResizeFocus::SOUTH_MIDDLE) { QPointF br = dashRect->rect().topRight(); dist = Util::GetPointDistLine(oppositePos,br,curPointItem); if (dist < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } dist = 20; } rectf.setHeight(dist); } else if(pos == KResizeFocus::EAST_MIDDLE) { QPointF br = dashRect->rect().bottomLeft(); dist = Util::GetPointDistLine(oppositePos,br,curPointItem); if (dist < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } dist = 20; } rectf.setWidth(dist); } else if(pos == KResizeFocus::WEST_MIDDLE) { QPointF br = dashRect->rect().bottomRight(); dist = Util::GetPointDistLine(oppositePos,br,curPointItem); if (dist < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } dist = 20; } rectf.setX(curPointItem.x()); rectf.setWidth(dist); } else if(pos == KResizeFocus::NORTH_WEST) { QPointF topRight = dashRect->rect().topRight(); QPointF bottomLeft = dashRect->rect().bottomLeft(); qreal distx = Util::GetPointDistLine(oppositePos,topRight,curPointItem); qreal disty = Util::GetPointDistLine(oppositePos,bottomLeft,curPointItem); if (distx < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } distx = 20; } if (disty < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } disty = 20; } rectf.setTopLeft(curPointItem); } else if(pos == KResizeFocus::NORTH_EAST) { QPointF topLeft = dashRect->rect().topLeft(); QPointF bottomRight = dashRect->rect().bottomRight(); qreal distx = Util::GetPointDistLine(oppositePos,topLeft,curPointItem); qreal disty = Util::GetPointDistLine(oppositePos,bottomRight,curPointItem); if (distx < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } distx = 20; } if (disty < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } disty = 20; } rectf.setTopRight(curPointItem); } else if(pos == KResizeFocus::SOUTH_EAST) { QPointF topRight = dashRect->rect().topRight(); QPointF bottomLeft = dashRect->rect().bottomLeft(); qreal disty = Util::GetPointDistLine(oppositePos,topRight,curPointItem); qreal distx = Util::GetPointDistLine(oppositePos,bottomLeft,curPointItem); if (distx < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } distx = 20; } if (disty < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } disty = 20; } rectf.setBottomRight(curPointItem); } else if(pos == KResizeFocus::SOUTH_WEST) { QPointF topLeft = dashRect->rect().topLeft(); QPointF bottomRight = dashRect->rect().bottomRight(); qreal disty = Util::GetPointDistLine(oppositePos,topLeft,curPointItem); qreal distx = Util::GetPointDistLine(oppositePos,bottomRight,curPointItem); if (distx < 20 || flagx != flagx1) { if (flagx) { curPointItem.setX(oppositePos.x() + 20); } else { curPointItem.setX(oppositePos.x() - 20); } distx = 20; } if (disty < 20 || flagy != flagy1) { if (flagy) { curPointItem.setY(oppositePos.y() + 20); } else { curPointItem.setY(oppositePos.y() - 20); } disty = 20; } rectf.setBottomLeft(curPointItem); } dashRect->setRect(rectf); } else if(myMode == MouseMode_ROTATE) { QPointF curPos = event->scenePos(); QPointF cpos = this->mapToScene(frame().center()); // qDebug()<<cpos; qreal angleLast = Util::ComputeAngle(mLastRotatePoint, cpos); qreal angleCur = Util::ComputeAngle(curPos, cpos); qreal angle = angleCur - angleLast; setAngle(angle); mLastRotatePoint = curPos; onRotate(); } else if(myMode == MouseMode_MOVE) { onMoving(); } else { QGraphicsItem::mouseMoveEvent(event); } }
void BaseEditor::paintEvent(QPaintEvent *e) { //copy from QPlainTextEditor QPainter painter(viewport()); Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout())); QPointF offset(contentOffset()); QRect er = e->rect(); QRect viewportRect = viewport()->rect(); bool editable = !isReadOnly(); QTextBlock block = firstVisibleBlock(); qreal maximumWidth = document()->documentLayout()->documentSize().width(); //margin qreal lineX = 0; if (conf->isDisplayRightColumnMargin()) { // Don't use QFontMetricsF::averageCharWidth here, due to it returning // a fractional size even when this is not supported by the platform. lineX = QFontMetricsF(document()->defaultFont()).width(QLatin1Char('X')) * conf->getRightMarginColumn() + offset.x() + 4; if (lineX < viewportRect.width()) { const QBrush background = QBrush(QColor(239, 239, 239)); painter.fillRect(QRectF(lineX, er.top(), viewportRect.width() - lineX, er.height()), background); const QColor col = (palette().base().color().value() > 128) ? Qt::black : Qt::white; const QPen pen = painter.pen(); painter.setPen(blendColors(background.isOpaque() ? background.color() : palette().base().color(), col, 32)); painter.drawLine(QPointF(lineX, er.top()), QPointF(lineX, er.bottom())); painter.setPen(pen); } } // Set a brush origin so that the WaveUnderline knows where the wave started painter.setBrushOrigin(offset); // keep right margin clean from full-width selection int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth) - document()->documentMargin(); er.setRight(qMin(er.right(), maxX)); painter.setClipRect(er); QAbstractTextDocumentLayout::PaintContext context = getPaintContext(); while (block.isValid()) { QRectF r = blockBoundingRect(block).translated(offset); QTextLayout *layout = block.layout(); if (!block.isVisible()) { offset.ry() += r.height(); block = block.next(); continue; } if (r.bottom() >= er.top() && r.top() <= er.bottom()) { QTextBlockFormat blockFormat = block.blockFormat(); QBrush bg = blockFormat.background(); if (bg != Qt::NoBrush) { QRectF contentsRect = r; contentsRect.setWidth(qMax(r.width(), maximumWidth)); fillBackground(&painter, contentsRect, bg); } QVector<QTextLayout::FormatRange> selections; int blpos = block.position(); int bllen = block.length(); for (int i = 0; i < context.selections.size(); ++i) { const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i); const int selStart = range.cursor.selectionStart() - blpos; const int selEnd = range.cursor.selectionEnd() - blpos; if (selStart < bllen && selEnd > 0 && selEnd > selStart) { QTextLayout::FormatRange o; o.start = selStart; o.length = selEnd - selStart; o.format = range.format; selections.append(o); } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection) && block.contains(range.cursor.position())) { // for full width selections we don't require an actual selection, just // a position to specify the line. that's more convenience in usage. QTextLayout::FormatRange o; QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos); o.start = l.textStart(); o.length = l.textLength(); if (o.start + o.length == bllen - 1) ++o.length; // include newline o.format = range.format; selections.append(o); } } bool drawCursor = ((editable || (textInteractionFlags() & Qt::TextSelectableByKeyboard)) && context.cursorPosition >= blpos && context.cursorPosition < blpos + bllen); bool drawCursorAsBlock = drawCursor && overwriteMode() ; if (drawCursorAsBlock) { if (context.cursorPosition == blpos + bllen - 1) { drawCursorAsBlock = false; } else { QTextLayout::FormatRange o; o.start = context.cursorPosition - blpos; o.length = 1; o.format.setForeground(palette().base()); o.format.setBackground(palette().text()); selections.append(o); } } layout->draw(&painter, offset, selections, er); if ((drawCursor && !drawCursorAsBlock) || (editable && context.cursorPosition < -1 && !layout->preeditAreaText().isEmpty())) { int cpos = context.cursorPosition; if (cpos < -1) cpos = layout->preeditAreaPosition() - (cpos + 2); else cpos -= blpos; layout->drawCursor(&painter, offset, cpos, cursorWidth()); } } offset.ry() += r.height(); if (offset.y() > viewportRect.height()) break; block = block.next(); } if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom() && (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) { painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background()); } }
void FieldView::drawTeamSpace(QPainter& p) { // Get the latest LogFrame const LogFrame* frame = _history->at(0).get(); if (showTeamNames) { // Draw Team Names QFont savedFont = p.font(); QFont fontstyle = p.font(); fontstyle.setPointSize(20); p.setFont(fontstyle); p.setPen(bluePen); drawText(p, QPointF(0, 4.75), QString(frame->team_name_blue().c_str()), true); // Blue p.setPen(yellowPen); drawText(p, QPointF(0, 1.75), QString(frame->team_name_yellow().c_str()), true); // Yellow p.setFont(savedFont); } // Block off half the field if (!frame->use_our_half()) { const float FX = Field_Dimensions::Current_Dimensions.FloorWidth() / 2; const float FY1 = -Field_Dimensions::Current_Dimensions.Border(); const float FY2 = Field_Dimensions::Current_Dimensions.Length() / 2; p.fillRect(QRectF(QPointF(-FX, FY1), QPointF(FX, FY2)), QColor(0, 0, 0, 128)); } if (!frame->use_opponent_half()) { const float FX = Field_Dimensions::Current_Dimensions.FloorWidth() / 2; const float FY1 = Field_Dimensions::Current_Dimensions.Length() / 2; const float FY2 = Field_Dimensions::Current_Dimensions.Length() + Field_Dimensions::Current_Dimensions.Border(); p.fillRect(QRectF(QPointF(-FX, FY1), QPointF(FX, FY2)), QColor(0, 0, 0, 128)); } if (showCoords) { drawCoords(p); } // History p.setBrush(Qt::NoBrush); QPainterPath ballTrail; for (unsigned int i = 0; i < 200 && i < _history->size(); ++i) { const LogFrame* oldFrame = _history->at(i).get(); if (oldFrame && oldFrame->has_ball()) { QPointF pos = qpointf(oldFrame->ball().pos()); if (i == 0) ballTrail.moveTo(pos); else ballTrail.lineTo(pos); } } QPen ballTrailPen(ballColor, 0.03); ballTrailPen.setCapStyle(Qt::RoundCap); p.setPen(ballTrailPen); p.drawPath(ballTrail); // Debug lines for (const DebugPath& path : frame->debug_paths()) { if (path.layer() < 0 || layerVisible(path.layer())) { tempPen.setColor(qcolor(path.color())); p.setPen(tempPen); std::vector<QPointF> pts; for (int i = 0; i < path.points_size(); ++i) { pts.push_back(qpointf(path.points(i))); } p.drawPolyline(pts.data(), pts.size()); } } for (const DebugRobotPath& path : frame->debug_robot_paths()) { if (path.layer() < 0 || layerVisible(path.layer())) { for (int i = 0; i < path.points_size() - 1; ++i) { const DebugRobotPath::DebugRobotPathPoint& from = path.points(i); const DebugRobotPath::DebugRobotPathPoint& to = path.points(i + 1); Geometry2d::Point avgVel = (Geometry2d::Point(path.points(i).vel()) + Geometry2d::Point(path.points(i + 1).vel())) / 2; float pcntMaxSpd = avgVel.mag() / MotionConstraints::defaultMaxSpeed(); QColor mixedColor(std::min((int)(255 * pcntMaxSpd), 255), 0, std::min((int)(255 * (1 - pcntMaxSpd)), 255)); QPen pen(mixedColor); pen.setCapStyle(Qt::RoundCap); pen.setWidthF(0.03); p.setPen(pen); const Geometry2d::Point fromPos = Geometry2d::Point(from.pos()); const Geometry2d::Point toPos = Geometry2d::Point(to.pos()); p.drawLine(fromPos.toQPointF(), toPos.toQPointF()); } } } // Debug circles for (const DebugCircle& c : frame->debug_circles()) { if (c.layer() < 0 || layerVisible(c.layer())) { tempPen.setColor(c.color()); p.setPen(tempPen); p.drawEllipse(qpointf(c.center()), c.radius(), c.radius()); } } // Debug arcs for (const DebugArc& a : frame->debug_arcs()) { if (a.layer() < 0 || layerVisible(a.layer())) { tempPen.setColor(a.color()); p.setPen(tempPen); auto c = a.center(); auto t1 = a.start(); auto t2 = a.end(); auto R = a.radius(); QRectF rect; rect.setX(-R + c.x()); rect.setY(-R + c.y()); rect.setWidth(R * 2); rect.setHeight(R * 2); t1 *= -(180 / M_PI) * 16; t2 *= -(180 / M_PI) * 16; p.drawArc(rect, t1, t2 - t1); } } // Debug text for (const DebugText& text : frame->debug_texts()) { if (text.layer() < 0 || layerVisible(text.layer())) { tempPen.setColor(text.color()); p.setPen(tempPen); drawText(p, qpointf(text.pos()), QString::fromStdString(text.text()), text.center()); } } // Debug polygons p.setPen(Qt::NoPen); for (const DebugPath& path : frame->debug_polygons()) { if (path.layer() < 0 || layerVisible(path.layer())) { if (path.points_size() < 3) { fprintf(stderr, "Ignoring DebugPolygon with %d points\n", path.points_size()); continue; } QColor color = qcolor(path.color()); color.setAlpha(64); p.setBrush(color); std::vector<QPointF> pts; for (int i = 0; i < path.points_size(); ++i) { pts.push_back(qpointf(path.points(i))); } p.drawConvexPolygon(pts.data(), pts.size()); } } p.setBrush(Qt::NoBrush); // maps robots to their comet trails, so we can draw a path of where each // robot has been over the past X frames the pair used as a key is of the // form (team, robot_id). Blue team = 1, yellow = 2. we only draw trails // for robots that exist in the current frame map<pair<int, int>, QPainterPath> cometTrails; /// populate @cometTrails with the past locations of each robot int pastLocationCount = 40; // number of past locations to show for (int i = 0; i < pastLocationCount + 1 && i < _history->size(); i++) { const LogFrame* oldFrame = _history->at(i).get(); if (oldFrame) { for (const LogFrame::Robot& r : oldFrame->self()) { pair<int, int> key(1, r.shell()); if (cometTrails.find(key) != cometTrails.end() || i == 0) { QPointF pt = qpointf(r.pos()); if (i == 0) cometTrails[key].moveTo(pt); else cometTrails[key].lineTo(pt); } } for (const LogFrame::Robot& r : oldFrame->self()) { pair<int, int> key(2, r.shell()); if (cometTrails.find(key) != cometTrails.end() || i == 0) { QPointF pt = qpointf(r.pos()); if (i == 0) cometTrails[key].moveTo(pt); else cometTrails[key].lineTo(pt); } } } } // draw robot comet trails const float cometTrailPenSize = 0.07; for (auto& kv : cometTrails) { QColor color = kv.first.first == 1 ? Qt::blue : Qt::yellow; QPen pen(color, cometTrailPenSize); pen.setCapStyle(Qt::RoundCap); p.setPen(pen); p.drawPath(kv.second); } // Text positioning vectors QPointF rtX = qpointf(Geometry2d::Point(0, 1).rotated(-_rotate * 90)); QPointF rtY = qpointf(Geometry2d::Point(-1, 0).rotated(-_rotate * 90)); // Opponent robots for (const LogFrame::Robot& r : frame->opp()) { drawRobot(p, !frame->blue_team(), r.shell(), qpointf(r.pos()), r.angle(), r.ball_sense_status() == HasBall); } // Our robots int manualID = frame->manual_id(); for (const LogFrame::Robot& r : frame->self()) { QPointF center = qpointf(r.pos()); bool faulty = false; if (r.has_ball_sense_status() && (r.ball_sense_status() == Dazzled || r.ball_sense_status() == Failed)) { faulty = true; } if (r.has_kicker_works() && !r.kicker_works()) { // faulty = true; } for (int i = 0; i < r.motor_status().size(); ++i) { if (r.motor_status(i) != Good) { faulty = true; } } if (r.has_battery_voltage() && r.battery_voltage() <= 14.3f) { faulty = true; } drawRobot(p, frame->blue_team(), r.shell(), center, r.angle(), r.ball_sense_status() == HasBall, faulty); // Highlight the manually controlled robot if (manualID == r.shell()) { p.setPen(greenPen); const float r = Robot_Radius + .05; p.drawEllipse(center, r, r); } // Robot text QPointF textPos = center - rtX * 0.2 - rtY * (Robot_Radius + 0.1); for (const DebugText& text : r.text()) { if (text.layer() < 0 || layerVisible(text.layer())) { tempPen.setColor(text.color()); p.setPen(tempPen); drawText(p, textPos, QString::fromStdString(text.text()), false); textPos -= rtY * 0.1; } } } // Current ball position and velocity if (frame->has_ball()) { QPointF pos = qpointf(frame->ball().pos()); QPointF vel = qpointf(frame->ball().vel()); p.setPen(ballPen); p.setBrush(ballColor); p.drawEllipse(QRectF(-Ball_Radius + pos.x(), -Ball_Radius + pos.y(), Ball_Diameter, Ball_Diameter)); if (!vel.isNull()) { p.drawLine(pos, QPointF(pos.x() + vel.x(), pos.y() + vel.y())); } } }
void QwtPieCurve::drawSlices(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap, int from, int to) const { const double x_width = fabs(xMap.p1() - xMap.p2()); const double x_center = (xMap.p1() + xMap.p2()) * 0.5 + d_horizontal_offset * 0.01 * x_width; const double y_center = (yMap.p1() + yMap.p2()) * 0.5; const double ray_x = d_pie_ray * 0.005 * qMin(x_width, fabs(yMap.p1() - yMap.p2())); const double view_angle_rad = d_view_angle * M_PI / 180.0; const double ray_y = ray_x * sin(view_angle_rad); const double thick = 0.01 * d_thickness * ray_x * cos(view_angle_rad); QRectF pieRect; pieRect.setX(x_center - ray_x); pieRect.setY(y_center - ray_y); pieRect.setWidth(2 * ray_x); pieRect.setHeight(2 * ray_y); QRectF pieRect2 = pieRect; pieRect2.translate(0, thick); double sum = 0.0; for (int i = from; i <= to; i++) sum += y(i); const int sign = d_counter_clockwise ? 1 : -1; const int size = dataSize(); double *start_angle = new double[size]; double *end_angle = new double[size]; double aux_angle = d_start_azimuth; for (int i = from; i <= to; i++) { double a = -sign * y(i) / sum * 360.0; start_angle[i] = aux_angle; double end = aux_angle + a; if (end >= 360) end -= 360; else if (end < 0) end += 360; end_angle[i] = end; aux_angle = end; } int angle = (int)(5760 * d_start_azimuth / 360.0); if (d_counter_clockwise) angle = (int)(5760 * (1 - d_start_azimuth / 360.0)); painter->save(); QLocale locale = (static_cast<Plot *>(plot()))->locale(); for (int i = from; i <= to; i++) { const double yi = y(i); const double q = yi / sum; const int value = (int)(q * 5760); painter->setPen(QwtPlotCurve::pen()); painter->setBrush(QBrush(color(i), QwtPlotCurve::brush().style())); double deg = q * 360; double start_3D_view_angle = start_angle[i]; double end_3D_view_angle = end_angle[i]; if (d_counter_clockwise) { start_3D_view_angle = end_angle[i]; end_3D_view_angle = start_angle[i]; } bool draw3D = false; if (deg <= 180 && start_3D_view_angle >= 0 && start_3D_view_angle < 180) { if ((end_3D_view_angle > 180 && end_3D_view_angle > start_3D_view_angle)) { deg = 180 - start_3D_view_angle; end_3D_view_angle = 180.0; } draw3D = true; } else if (start_3D_view_angle >= 180 && end_3D_view_angle < start_3D_view_angle) { if (end_3D_view_angle > 180) end_3D_view_angle = 180; deg = end_3D_view_angle; start_3D_view_angle = 0; draw3D = true; } else if (deg > 180 && start_3D_view_angle >= 180) { deg = 180; end_3D_view_angle = 180; start_3D_view_angle = 0; draw3D = true; } if (draw3D) { double rad = start_3D_view_angle / 180.0 * M_PI; QPointF start(x_center + ray_x * cos(rad), y_center + ray_y * sin(rad)); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); path.arcTo(pieRect2, -start_3D_view_angle, -deg); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -end_3D_view_angle, deg); painter->drawPath(path); } else { if (start_3D_view_angle >= 0 && start_3D_view_angle < 180) { if (end_3D_view_angle > 180) end_3D_view_angle = 0; double rad = start_3D_view_angle / 180.0 * M_PI; QPointF start(x_center + ray_x * cos(rad), y_center + ray_y * sin(rad)); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); deg = 180 - start_3D_view_angle; path.arcTo(pieRect2, -start_3D_view_angle, -deg); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -180, deg); painter->drawPath(path); path.moveTo(QPointF(x_center + ray_x, y_center)); aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() + thick); path.arcTo(pieRect2, 0, -end_3D_view_angle); aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -end_3D_view_angle, end_3D_view_angle); painter->drawPath(path); } } painter->drawPie(pieRect, sign * angle, sign * value); angle += value; if (i >= d_texts_list.size()) continue; PieLabel *l = d_texts_list[i]; if (l) { QString s; if (d_auto_labeling) { if (d_categories) s += QString::number(d_table_rows[i]) + "\n"; if (d_values && d_percentages) s += locale.toString(yi, 'g', 4) + " (" + locale.toString(q * 100, 'g', 4) + "%)"; else if (d_values) s += locale.toString(yi, 'g', 4); else if (d_percentages) s += locale.toString(q * 100, 'g', 4) + "%"; l->setText(s); if (l->isHidden()) l->show(); } else l->setText(l->customText()); if (d_fixed_labels_pos) { double a_deg = start_angle[i] - sign * q * 180.0; if (a_deg > 360) a_deg -= 360.0; double a_rad = a_deg * M_PI / 180.0; double rx = ray_x * (1 + 0.01 * d_edge_dist); const double x = x_center + rx * cos(a_rad); double ry = ray_y * (1 + 0.01 * d_edge_dist); double y = y_center + ry * sin(a_rad); if (a_deg > 0 && a_deg < 180) y += thick; double dx = xMap.invTransform(x - l->width() / 2); double dy = yMap.invTransform(y - l->height() / 2); l->setOriginCoord(dx, dy); } } } painter->restore(); delete[] start_angle; delete[] end_angle; }
void CollectionTreeItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if( index.parent().isValid() ) // not a root item { QStyledItemDelegate::paint( painter, option, index ); return; } const bool isRTL = QApplication::isRightToLeft(); const QPoint topLeft = option.rect.topLeft(); const int width = m_view->viewport()->size().width() - 4; const int height = sizeHint( option, index ).height(); const int iconWidth = 32; const int iconHeight = 32; const int iconPadX = 4; const bool hasCapacity = index.data( CustomRoles::HasCapacityRole ).toBool(); const int actionCount = index.data( CustomRoles::DecoratorRoleCount ).toInt(); painter->save(); QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter ); if ( option.state & QStyle::State_Selected ) painter->setPen( App::instance()->palette().highlightedText().color() ); else painter->setPen( App::instance()->palette().text().color() ); painter->setRenderHint( QPainter::Antialiasing ); const int iconYPadding = ( height - iconHeight ) / 2; QPoint iconPos( topLeft + QPoint( iconPadX, iconYPadding ) ); if( isRTL ) iconPos.setX( width - iconWidth - iconPadX ); painter->drawPixmap( iconPos, index.data( Qt::DecorationRole ).value<QIcon>().pixmap( iconWidth, iconHeight ) ); QStyleOption expanderOption( option ); QStyle::PrimitiveElement expandedPrimitive; if( isRTL ) { expandedPrimitive = QStyle::PE_IndicatorArrowLeft; expanderOption.rect.setLeft( iconPadX ); } else { expandedPrimitive = QStyle::PE_IndicatorArrowRight; expanderOption.rect.setLeft( option.rect.right() - iconPadX - iconWidth ); } expanderOption.rect.setWidth( iconWidth ); //FIXME: CollectionTreeItemModelBase::hasChildren() returns true for root items regardless if( m_view->model()->hasChildren( index ) ) { if( m_view->isExpanded( index ) ) { QApplication::style()->drawPrimitive( QStyle::PE_IndicatorArrowDown, &expanderOption, painter ); } else { QApplication::style()->drawPrimitive( expandedPrimitive, &expanderOption, painter ); } } const QString collectionName = index.data( Qt::DisplayRole ).toString(); const QString bylineText = index.data( CustomRoles::ByLineRole ).toString(); const int actionsRectWidth = actionCount > 0 ? (ACTIONICON_SIZE * actionCount + 2*2/*margin*/) : 0; const int iconRight = topLeft.x() + iconWidth + iconPadX * 2; const int infoRectLeft = isRTL ? actionsRectWidth : iconRight; const int infoRectWidth = width - iconRight; const int titleRectWidth = infoRectWidth - actionsRectWidth; QRectF titleRect; titleRect.setLeft( infoRectLeft ); titleRect.setTop( option.rect.top() + iconYPadding ); titleRect.setWidth( titleRectWidth ); titleRect.setHeight( m_bigFm->boundingRect( collectionName ).height() ); painter->setFont( m_bigFont ); painter->drawText( titleRect, Qt::AlignLeft, collectionName ); const bool isHover = option.state & QStyle::State_MouseOver; QPoint cursorPos = m_view->mapFromGlobal( QCursor::pos() ); cursorPos.ry() -= 20; // Where the f**k does this offset come from. I have _ZERO_ idea. painter->setFont( m_smallFont ); // we want smaller font for both subtitle and capacity bar //show the bylinetext or the capacity (if available) when hovering if( isHover && hasCapacity ) { qreal bytesUsed = index.data( CustomRoles::UsedCapacityRole ).toReal(); qreal bytesTotal = index.data( CustomRoles::TotalCapacityRole ).toReal(); const int percentage = (bytesTotal > 0.0) ? qRound( 100.0 * bytesUsed / bytesTotal ) : 100; KCapacityBar capacityBar( KCapacityBar::DrawTextInline ); capacityBar.setValue( percentage ); capacityBar.setText( i18nc( "Example: 3.5 GB free (unit is part of %1)", "%1 free", KGlobal::locale()->formatByteSize( bytesTotal - bytesUsed, 1 ) ) ); QRect capacityRect; capacityRect.setLeft( isRTL ? 0 : infoRectLeft ); capacityRect.setTop( titleRect.bottom() ); //makeing sure capacity bar does not overlap expander capacityRect.setWidth( infoRectWidth - iconWidth ); capacityRect.setHeight( qBound( CAPACITYRECT_MIN_HEIGHT, capacityBar.minimumSizeHint().height(), CAPACITYRECT_MAX_HEIGHT ) ); capacityBar.drawCapacityBar( painter, capacityRect ); } else { QRectF textRect; textRect.setLeft( infoRectLeft ); textRect.setTop( titleRect.bottom() ); textRect.setWidth( titleRectWidth ); textRect.setHeight( m_smallFm->boundingRect( bylineText ).height() ); painter->drawText( textRect, Qt::TextWordWrap, bylineText ); } if( isHover && ( actionCount > 0 ) ) { const QList<QAction*> actions = index.data( CustomRoles::DecoratorRole ).value<QList<QAction*> >(); QRect decoratorRect; if( isRTL ) //actions should appear to the right of the expander decoratorRect.setLeft( expanderOption.rect.right() + iconPadX ); else //actions should appear left of the expander decoratorRect.setLeft( expanderOption.rect.left() - actionCount * ( ACTIONICON_SIZE + iconPadX ) ); decoratorRect.setTop( option.rect.top() + iconYPadding ); decoratorRect.setWidth( actionsRectWidth ); decoratorRect.setHeight( ACTIONICON_SIZE ); QPoint actionTopLeftBase = decoratorRect.topLeft(); const QSize iconSize = QSize( ACTIONICON_SIZE, ACTIONICON_SIZE ); int i = 0; foreach( QAction * action, actions ) { QIcon icon = action->icon(); int x = actionTopLeftBase.x() + i * ( ACTIONICON_SIZE + iconPadX ); QPoint actionTopLeft = QPoint( x, actionTopLeftBase.y() ); QRect iconRect( actionTopLeft, iconSize ); const bool isOver = isHover && iconRect.contains( cursorPos ); icon.paint( painter, iconRect, Qt::AlignCenter, isOver ? QIcon::Active : QIcon::Normal, isOver ? QIcon::On : QIcon::Off ); i++; } // Store the Model index for lookups for clicks. FAIL. QPersistentModelIndex persistentIndex( index ); s_indexDecoratorRects.insert( persistentIndex, decoratorRect ); }
void QwtPieCurve::drawDisk(QPainter *painter, const QwtScaleMap &xMap, const QwtScaleMap &yMap) const { const double x_width = fabs(xMap.p1() - xMap.p2()); const double x_center = (xMap.p1() + xMap.p2()) * 0.5 + d_horizontal_offset * 0.01 * x_width; const double y_center = (yMap.p1() + yMap.p2()) * 0.5; const double ray_x = d_pie_ray * 0.005 * qMin(x_width, fabs(yMap.p1() - yMap.p2())); const double view_angle_rad = d_view_angle * M_PI / 180.0; const double ray_y = ray_x * sin(view_angle_rad); const double thick = 0.01 * d_thickness * ray_x * cos(view_angle_rad); QRectF pieRect; pieRect.setX(x_center - ray_x); pieRect.setY(y_center - ray_y); pieRect.setWidth(2 * ray_x); pieRect.setHeight(2 * ray_y); QRectF pieRect2 = pieRect; pieRect2.translate(0, thick); painter->save(); painter->setPen(QwtPlotCurve::pen()); painter->setBrush(QBrush(color(0), QwtPlotCurve::brush().style())); QPointF start(x_center + ray_x, y_center); QPainterPath path(start); path.lineTo(start.x(), start.y() + thick); path.arcTo(pieRect2, 0, -180.0); QPointF aux = path.currentPosition(); path.lineTo(aux.x(), aux.y() - thick); path.arcTo(pieRect, -180.0, 180.0); painter->drawPath(path); painter->drawEllipse(pieRect); if (d_texts_list.size() > 0) { PieLabel *l = d_texts_list[0]; if (l) { QString s; if (d_auto_labeling) { if (d_categories) s += QString::number(d_table_rows[0]) + "\n"; if (d_values && d_percentages) s += (static_cast<Plot *>(plot()))->locale().toString(y(0), 'g', 4) + " (100%)"; else if (d_values) s += (static_cast<Plot *>(plot()))->locale().toString(y(0), 'g', 4); else if (d_percentages) s += "100%"; l->setText(s); if (l->isHidden()) l->show(); } else l->setText(l->customText()); if (d_fixed_labels_pos) { double a_deg = d_start_azimuth + 180.0; if (a_deg > 360) a_deg -= 360; double a_rad = a_deg * M_PI / 180.0; double rx = ray_x * (1 + 0.01 * d_edge_dist); const double x = x_center + rx * cos(a_rad); double ry = ray_y * (1 + 0.01 * d_edge_dist); double y = y_center + ry * sin(a_rad); if (a_deg > 0 && a_deg < 180) y += thick; double dx = xMap.invTransform(x - l->width() / 2); double dy = yMap.invTransform(y - l->height() / 2); l->setOriginCoord(dx, dy); } } } painter->restore(); }
void VerticalMenu::CalculatePositions(QVector<QPointF> &positions) { QRectF boundaries = boundaries_; //this is needed when rect size is smaller than the cards max size because we need to shrink the highlighted card too qreal additional_shrinkage = 0; if(current_scale_factor_ != scale_factor_) { additional_shrinkage = card_max_size_.width() - (card_max_size_.width()*(current_card_max_size_.height() / (card_max_size_.height()))); additional_shrinkage/=2; } int visible_objects = max_visible_objects_; boundaries.setWidth(boundaries.width() - current_card_max_size_.width()); qreal width_radius = boundaries.width()/2; qreal last_left_pos = width_radius, last_right_pos = width_radius; qreal y_coord = 0; if(type_ == VerticalMenu::VERTICAL_TOP) { y_coord = boundaries.top(); } else if(type_ == VerticalMenu::VERTICAL_MID) { y_coord = boundaries.top() + ((boundaries.height()/2) - (current_card_max_size_.height()/2)); } else if(type_ == VerticalMenu::VERTICAL_BOTTOM) { y_coord = boundaries.bottom() - (current_card_max_size_.height()); } QPointF pos; pos.setX(boundaries.left()+width_radius); pos.setY(y_coord); positions.push_back(pos); //calculate the rest of the positions for (int i=1; i<visible_objects; i++) { qreal current_vert_pos; QPointF pos; qreal shrinkage = card_max_size_.width() - (card_max_size_.width() * pow(current_scale_factor_ ,(i+1)/2)); shrinkage/=2; if(i%2==1) { //Vertical Pos if(type_ == VerticalMenu::VERTICAL_BOTTOM) { if(i==1 && (scale_factor_!= current_scale_factor_)) { y_coord += (current_card_max_size_.height() - (card_max_size_.height() * current_scale_factor_)); } else { y_coord += card_max_size_.height()*pow(current_scale_factor_ ,((i+1)/2)-1) - (card_max_size_.height() * pow(current_scale_factor_ ,(i+1)/2)); } } else if(type_ == VerticalMenu::VERTICAL_MID) { if(i==1 && (scale_factor_!= current_scale_factor_)) { y_coord += (current_card_max_size_.height() - (card_max_size_.height() * current_scale_factor_))/2; } else { y_coord += (card_max_size_.height()*pow(current_scale_factor_ ,((i+1)/2)-1) - (card_max_size_.height() * pow(current_scale_factor_ ,(i+1)/2)))/2; } } //Horizontal Pos current_vert_pos = last_right_pos + current_card_max_size_.width() -shrinkage + current_gap_; if(i==1) { current_vert_pos -= additional_shrinkage; } last_right_pos = current_vert_pos - shrinkage; } else { current_vert_pos = last_left_pos - current_card_max_size_.width() + shrinkage - current_gap_; if(i==2) { current_vert_pos += additional_shrinkage; } last_left_pos = current_vert_pos + shrinkage; } pos.setX(current_vert_pos+boundaries.left()); pos.setY(y_coord); positions.push_back(pos); } hide_point_.setX(positions.first().x()); hide_point_.setY(positions.first().y()); }
QFileInfo saveWidgetAsImage(QObject* wid, const QRect& r, const QString& dialogTitle, const QString& defaultPath, const AppSettings & appSetting) { QFileInfo fileInfo; QGraphicsScene* scene = 0; QWidget* widget = dynamic_cast<QWidget*>(wid); GraphView* mGraph = dynamic_cast<GraphView*>(wid); if(!mGraph && !widget) { scene = dynamic_cast<QGraphicsScene*>(wid); if(!scene) return fileInfo; } QString filter = QObject::tr("Image (*.png);;Photo (*.jpg);; Windows Bitmap (*.bmp);;Scalable Vector Graphics (*.svg)"); QString fileName = QFileDialog::getSaveFileName(qApp->activeWindow(), dialogTitle, defaultPath, filter); if(!fileName.isEmpty()) { fileInfo = QFileInfo(fileName); QString fileExtension = fileInfo.suffix(); //QString fileExtension = fileName.(".svg"); // bool asSvg = fileName.endsWith(".svg"); // if(asSvg) //QFontMetrics fm((scene ? qApp->font() : widget->font())); float heightText = r.height()/50; //fm.height() + 30; /*if (heightText<10) { heightText = 10; }*/ if(fileExtension == "svg") { if(mGraph) { mGraph->saveAsSVG(fileName, "Title", "Description",true); } else if(scene) { QSvgGenerator svgGen; svgGen.setFileName(fileName); svgGen.setSize(r.size()); svgGen.setViewBox(QRect(0, 0, r.width(), r.height())); svgGen.setDescription(QObject::tr("SVG scene drawing ")); //qDebug()<<"export scene as SVG"; QPainter p; p.begin(&svgGen); scene->render(&p, r, r); p.end(); } else if(widget) { saveWidgetAsSVG(widget, r, fileName); } } else { // save PNG //int versionHeight = 20; //qreal pr = 1;//qApp->devicePixelRatio(); /* qreal prh= 32000. / ( r.height() + versionHeight) ; // QImage axes are limited to 32767x32767 pixels qreal prw= 32000. / r.width() ; qreal pr = (prh<prw)? prh : prw; if (pr>4) { pr=4; } */ // ------------------------------- // Get preferences // ------------------------------- short pr = appSetting.mPixelRatio; short dpm = appSetting.mDpm; short quality = appSetting.mImageQuality; // ------------------------------- // Create the image // ------------------------------- QImage image(r.width() * pr, (r.height() + heightText) * pr , QImage::Format_ARGB32_Premultiplied); if(image.isNull()){ qDebug() << "Cannot export null image!"; return fileInfo; } // ------------------------------- // Set image properties // ------------------------------- image.setDotsPerMeterX(dpm * 11811.024 / 300.); image.setDotsPerMeterY(dpm * 11811.024 / 300.); image.setDevicePixelRatio(pr); // ------------------------------- // Fill background // ------------------------------- if (fileExtension == "jpg") { image.fill(Qt::white); } else { image.fill(Qt::transparent); } // ------------------------------- // Create painter // ------------------------------- QPainter p; p.begin(&image); p.setRenderHint(QPainter::Antialiasing); // ------------------------------- // If widget, draw with or without axis // ------------------------------- if(widget){ //p.setFont(widget->font()); widget->render(&p, QPoint(0, 0), QRegion(r.x(), r.y(), r.width(), r.height())); } // ------------------------------- // If scene... // ------------------------------- else if(scene){ QRectF srcRect = r; srcRect.setX(r.x()); srcRect.setY(r.y()); srcRect.setWidth(r.width() * pr); srcRect.setHeight(r.height() * pr); QRectF tgtRect = image.rect(); tgtRect.adjust(0, 0, 0, -heightText * pr); scene->render(&p, tgtRect, srcRect); } // ------------------------------- // Write application and version // ------------------------------- QFont ft = scene ? qApp->font() : widget->font(); ft.setPixelSize(heightText); p.setFont(ft); p.setPen(Qt::black); p.drawText(0, r.height(), r.width(), heightText, Qt::AlignCenter, qApp->applicationName() + " " + qApp->applicationVersion()); p.end(); // ------------------------------- // Save file // ------------------------------- image.save(fileName, fileExtension.toUtf8(), quality); //image.save(fileName, formatExt); /*QImageWriter writer; writer.setFormat("jpg"); writer.setQuality(100); writer.setFileName(fileName+"_jpg"); writer.write(image);*/ } } return fileInfo; }
void SceneImageExporter::printScene(QGraphicsScene *scene, QPrinter& printer, QString fileName, QString documentName, int printingFlags) { if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive)) { printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } else { //set page margins if I have to print on paper. printer.setPageMargins(10,10,10,10,QPrinter::Millimeter); } QPainter painter(&printer); QRectF sceneRect = scene->sceneRect(); double sceneRatio = scene->sceneRect().width()/scene->sceneRect().height(); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); QRect pageRect = QRect( printer.pageRect().top()+top, printer.pageRect().left()+left, printer.pageRect().width()-(left+right), printer.pageRect().height()-(top+bottom)); int xSize, ySize, dxSize, dySize, xPages, yPages; double fWidth, fHeight, fHeightStep, fWidthStep; double pageRectRatio = (double)pageRect.width()/(double)pageRect.height(); xSize = (int)((double)(3*pageRect.width()) * 1.0); ySize = (int)((double)(3*pageRect.height()) * .9); dxSize = (int)((double)(3*pageRect.width()) * .05); dySize = (int)((double)(3*pageRect.height()) * .05); xPages = 1+ (((int)sceneRect.width()) / xSize); yPages = 1+ (((int)sceneRect.height()) / ySize); if (SIEOptions::ScaleToSceneHeight(printingFlags)) { yPages = 1; xPages = 1+(int)( (double)yPages *sceneRatio); ySize = (int) ((double)scene->sceneRect().height()*.9); xSize = (int) ( (double)ySize * pageRectRatio); dySize = (int) (.05 * (double)scene->sceneRect().height()*.9); dxSize = (int) ( .05 *(double)ySize * pageRectRatio); } if (SIEOptions::ScaleToSceneWidth(printingFlags)) { xPages = 1; yPages = 1+(int)( (double)yPages / sceneRatio); } fWidth = 1.0* (double)pageRect.width(); fHeight = .9* (double)pageRect.height(); fHeightStep = .15* (double)pageRect.height(); fWidthStep = fHeightStep * sceneRatio; bool bNewPage = false; double fWidth2 = fWidth * .9; double fHeight2 = fHeight * .9; QPainterPath path; QRectF rectOuter; rectOuter.setLeft((double)pageRect.left()); rectOuter.setTop((double)pageRect.top()); rectOuter.setWidth(fWidth2); rectOuter.setHeight(fHeight2); path.addRect(rectOuter); QRectF rectInner(rectOuter); rectInner.setTopLeft(QPointF( rectInner.left()+fWidth2/20, rectInner.top()+fHeight2/20)); rectInner.setSize(QSizeF(fWidth2*.9,fHeight2*.9)); path.addRect(rectInner); painter.begin(&printer); QBrush shadowBrush = QBrush(QColor(192,192,192,64)); QBrush transparent = QBrush(QColor(192,192,192,16)); //QPen pen = QPen(QColor (65,65,65,192)); QPen pen = QPen(QColor (255,0,0,192)); QFont font = QFont("Droid Sans"); font.setBold(true); font.setPointSizeF(16.0); QFont fontb = QFont("Droid Sans"); fontb.setBold(false); fontb.setPointSizeF(11.0); //double fh = fHeightStep / yPages; //double fw = fWidthStep / xPages; double tinyRectXRatio = fWidthStep / scene->sceneRect().width(); double tinyRectYRatio = fHeightStep / scene->sceneRect().height(); int nCur = 0; int nMax = yPages*xPages; for (int y = 0; y < yPages; y++) { for (int x = 0; x < xPages; x++) { nCur = (y*xPages)+(x+1); if (bNewPage) printer.newPage(); else bNewPage = true; QRectF targetRect = QRectF((double)pageRect.left(),(double)pageRect.top(),fWidth2,fHeight2); QRectF sourceRect = QRectF ( (double)(x*xSize)+sceneRect.left()-(double)dxSize, (double)(y*ySize)+sceneRect.top()-(double)dySize, (double)(xSize)+2*(double)dxSize, (double)(ySize)+2*(double)dySize); QRectF targetRect2 = QRectF( (double)targetRect.left()+10, (double)targetRect.top()+ fHeight2+10, fWidthStep, fHeightStep); QRectF tinyRect; tinyRect.setLeft((sourceRect.left()-sceneRect.left()) * tinyRectXRatio+targetRect2.left()); tinyRect.setTop((sourceRect.top()-sceneRect.top()) * tinyRectYRatio+ targetRect2.top()); tinyRect.setWidth(sourceRect.width()*tinyRectXRatio); tinyRect.setHeight(sourceRect.height()*tinyRectYRatio); scene->render(&painter,targetRect, sourceRect); painter.setPen(pen); painter.setBrush(transparent); painter.drawRect(targetRect2); scene->render(&painter,targetRect2, scene->sceneRect(), Qt::IgnoreAspectRatio); painter.setPen(pen); painter.setBrush(shadowBrush); painter.drawPath(path); painter.drawRect(tinyRect); QFontMetricsF metrics(font); int nDelta = 0; painter.setFont(font); painter.setBrush(QBrush(QColor("black"))); painter.drawText( targetRect2.left()+fWidthStep+10, targetRect2.top()+metrics.height(), documentName); nDelta+= (int)metrics.height()+10; painter.setFont(fontb); QFontMetricsF metricsb(fontb); nDelta+= (int)metricsb.height(); QString txt = QString().sprintf("Folio [%d,%d] -- page %d of %d",x,y,nCur, nMax); painter.drawText( targetRect2.left()+fWidthStep+10, targetRect2.top()+nDelta, txt); } } painter.end(); }
void ZCircle::displayHelper(ZPainter *painter, int stackFocus, EDisplayStyle style) const { UNUSED_PARAMETER(style); #if defined(_QT_GUI_USED_) double adjustedRadius = getAdjustedRadius(m_r); double dataFocus = stackFocus - painter->getZOffset(); bool visible = false; const QBrush &oldBrush = painter->getBrush(); const QPen &oldPen = painter->getPen(); double alpha = oldPen.color().alphaF(); if (stackFocus == -1) { visible = true; } else { if (isCuttingPlane(m_center.z(), m_r, dataFocus, m_zScale)) { double h = fabs(m_center.z() - dataFocus) / m_zScale; double r = 0.0; if (m_r > h) { r = sqrt(m_r * m_r - h * h); adjustedRadius = getAdjustedRadius(r); //adjustedRadius = r + getPenWidth() * 0.5; visible = true; } else { //too small, show at least one plane //adjustedRadius = getPenWidth() * 0.5; r = 0.1; adjustedRadius = getAdjustedRadius(r); visible = true; } if (hasVisualEffect(VE_OUT_FOCUS_DIM)) { alpha *= r * r / m_r / m_r; //alpha *= alpha; } } } if (visible) { if (!hasVisualEffect(VE_NO_CIRCLE)) { //qDebug() << painter->brush().color(); QColor color = painter->getPenColor(); color.setAlphaF(alpha); painter->setPen(color); painter->drawEllipse(QPointF(m_center.x(), m_center.y()), adjustedRadius, adjustedRadius); } } if (hasVisualEffect(VE_BOUND_BOX)) { QRectF rect; double halfSize = adjustedRadius; if (m_usingCosmeticPen) { halfSize += 0.5; } rect.setLeft(m_center.x() - halfSize); rect.setTop(m_center.y() - halfSize); rect.setWidth(halfSize * 2); rect.setHeight(halfSize * 2); painter->setBrush(Qt::NoBrush); QPen pen = oldPen; if (visible) { pen.setStyle(Qt::SolidLine); } else { pen.setStyle(Qt::DotLine); } pen.setCosmetic(m_usingCosmeticPen); painter->setPen(pen); #if 0 //for future versions QPen pen = oldPen; QVector<qreal> pattern; pattern << 1 << 2; pen.setDashPattern(pattern); painter->setPen(pen); painter->drawRect(rect); pen.setColor(Qt::black); pen.setDashOffset(1.5); painter->setPen(pen); #endif //QPainter::CompositionMode oldMode = painter->compositionMode(); //painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination); painter->drawRect(rect); //painter->setCompositionMode(oldMode); } painter->setBrush(oldBrush); painter->setPen(oldPen); #endif }
QPixmap QgsFontButton::createDragIcon( QSize size, const QgsTextFormat *tempFormat, const QFont *tempFont ) const { if ( !tempFormat ) tempFormat = &mFormat; if ( !tempFont ) tempFont = &mFont; //create an icon pixmap QPixmap pixmap( size.width(), size.height() ); pixmap.fill( Qt::transparent ); QPainter p; p.begin( &pixmap ); p.setRenderHint( QPainter::Antialiasing ); QRect rect( 0, 0, size.width(), size.height() ); if ( mMode == ModeQFont || tempFormat->color().lightnessF() < 0.7 ) { p.setBrush( QBrush( QColor( 255, 255, 255 ) ) ); p.setPen( QPen( QColor( 150, 150, 150 ), 0 ) ); } else { p.setBrush( QBrush( QColor( 0, 0, 0 ) ) ); p.setPen( QPen( QColor( 100, 100, 100 ), 0 ) ); } p.drawRect( rect ); p.setBrush( Qt::NoBrush ); p.setPen( Qt::NoPen ); switch ( mMode ) { case ModeTextRenderer: { QgsRenderContext context; QgsMapToPixel newCoordXForm; newCoordXForm.setParameters( 1, 0, 0, 0, 0, 0 ); context.setMapToPixel( newCoordXForm ); context.setScaleFactor( QgsApplication::desktop()->logicalDpiX() / 25.4 ); context.setUseAdvancedEffects( true ); context.setPainter( &p ); // slightly inset text to account for buffer/background double xtrans = 0; if ( tempFormat->buffer().enabled() ) xtrans = context.convertToPainterUnits( tempFormat->buffer().size(), tempFormat->buffer().sizeUnit(), tempFormat->buffer().sizeMapUnitScale() ); if ( tempFormat->background().enabled() && tempFormat->background().sizeType() != QgsTextBackgroundSettings::SizeFixed ) xtrans = std::max( xtrans, context.convertToPainterUnits( tempFormat->background().size().width(), tempFormat->background().sizeUnit(), tempFormat->background().sizeMapUnitScale() ) ); double ytrans = 0.0; if ( tempFormat->buffer().enabled() ) ytrans = std::max( ytrans, context.convertToPainterUnits( tempFormat->buffer().size(), tempFormat->buffer().sizeUnit(), tempFormat->buffer().sizeMapUnitScale() ) ); if ( tempFormat->background().enabled() ) ytrans = std::max( ytrans, context.convertToPainterUnits( tempFormat->background().size().height(), tempFormat->background().sizeUnit(), tempFormat->background().sizeMapUnitScale() ) ); QRectF textRect = rect; textRect.setLeft( xtrans ); textRect.setWidth( textRect.width() - xtrans ); textRect.setTop( ytrans ); if ( textRect.height() > 300 ) textRect.setHeight( 300 ); if ( textRect.width() > 2000 ) textRect.setWidth( 2000 ); QgsTextRenderer::drawText( textRect, 0, QgsTextRenderer::AlignCenter, QStringList() << tr( "Aa" ), context, *tempFormat ); break; } case ModeQFont: { p.setBrush( Qt::NoBrush ); p.setPen( QColor( 0, 0, 0 ) ); p.setFont( *tempFont ); QRectF textRect = rect; textRect.setLeft( 2 ); p.drawText( textRect, Qt::AlignVCenter, tr( "Aa" ) ); break; } } p.end(); return pixmap; }
void QColorTabWidget::drawTab( QPainter& p, QRect& rectTab, const TabInfo& ti, bool bHover, bool bActive, bool bNotify ) { QPainterPath tabPath; QPainterPath tabS; int nDiameter = 3 << 1; QRectF arcRect( 0, 0, nDiameter, nDiameter ); if (isHorzTab()) { // Horz-Tab tabPath.moveTo( rectTab.bottomLeft() ); tabPath.lineTo( rectTab.left(), rectTab.top()+nDiameter/2); tabS.moveTo( rectTab.left(), rectTab.top()+nDiameter/2 ); arcRect.moveTo( rectTab.topLeft() ); tabPath.arcTo( arcRect, 180, -90 ); tabS.arcTo( arcRect, 180, -90 ); tabPath.lineTo( rectTab.right()-nDiameter/2, rectTab.top() ); tabS.lineTo( rectTab.right()-nDiameter/2, rectTab.top() ); arcRect.moveTo( rectTab.right()-nDiameter, rectTab.top() ); tabPath.arcTo( arcRect, 90, -90 ); tabS.arcTo( arcRect, 90, -90 ); tabPath.lineTo( rectTab.bottomRight() ); tabS.closeSubpath(); //tabPath.closeSubpath(); } else { // Vert-Tab tabPath.moveTo( rectTab.right(), rectTab.y() ); tabPath.lineTo( rectTab.x()+nDiameter, rectTab.y() ); tabS.moveTo( rectTab.x()+nDiameter, rectTab.y() ); arcRect.moveTo(rectTab.topLeft()); tabPath.arcTo( arcRect, -270, 90 ); tabS.arcTo( arcRect, -270, 90 ); arcRect.moveTo(rectTab.x(), rectTab.bottom()-nDiameter); tabPath.arcTo( arcRect, -180, 90 ); tabS.arcTo( arcRect, -180, 90 ); tabPath.moveTo( rectTab.left()+nDiameter, rectTab.bottom() ); tabPath.lineTo( rectTab.right(), rectTab.bottom() ); tabS.closeSubpath(); //tabPath.closeSubpath(); } QColor colorBody; if (bNotify && (m_nBlinkCount % 2 == 0)) { colorBody = QColor(252, 209, 211); } else { if (bActive) colorBody = QColor(255, 255, 255); else colorBody = QColor(0xF5, 0xF5, 0xF5); } p.fillPath( tabPath, QBrush(colorBody) ); QColor colorStart = bActive ? ti.clrTab : (bHover ? QColor(255, 190, 60, 200) : QColor(255, 255, 255, 200)); QColor colorEnd(255, 255, 255, 200); QRectF rectTabTip; rectTabTip = tabS.boundingRect(); QLinearGradient gradTip; if (!isHorzTab()) { gradTip.setStart(rectTabTip.left(), rectTabTip.center().y()); gradTip.setFinalStop(rectTabTip.right(), rectTabTip.center().y()); } else { gradTip.setStart(rectTabTip.center().x(), rectTabTip.top()); gradTip.setFinalStop(rectTabTip.center().x(), rectTabTip.bottom()); } gradTip.setColorAt( 0, colorStart ); gradTip.setColorAt( 1.f, colorEnd ); p.setBrush(Qt::NoBrush); p.setPen( QPen(QColor(160,160,160,100), 2.f) ); p.drawPath( tabPath ); p.setPen( QPen(QColor(160,160,160)) ); p.drawPath( tabPath ); p.fillPath( tabS, QBrush(gradTip) ); if (bActive || bHover) { p.setPen( colorStart ); p.drawPath( tabS ); } QRectF rectText; float fTextOffset = ti.pIconImage ? ti.pIconImage->width()+5.f : 0.f; if (isHorzTab()) { rectText.setX((float)rectTab.x() + fTextOffset); rectText.setY((float)rectTab.y() + nDiameter/2); rectText.setWidth((float)rectTab.width() - fTextOffset); rectText.setHeight((float)rectTab.height() - nDiameter/2); } else { rectText.setX((float)rectTab.x() + nDiameter/2 + fTextOffset); rectText.setY((float)rectTab.y()); rectText.setWidth((float)rectTab.width() - nDiameter/2 - fTextOffset); rectText.setHeight((float)rectTab.height()); } m_fntTab.setBold(bActive); p.setFont( m_fntTab ); if (ti.pIconImage) { int nIW = ti.pIconImage->width(); int nIH = ti.pIconImage->height(); p.drawImage( (int)(rectText.x()-fTextOffset), (int)(rectText.y()), *ti.pIconImage, 0, 0, nIW, nIH ); } int flags = Qt::AlignCenter|Qt::AlignVCenter|Qt::TextSingleLine; p.setPen( QColor(80,80,80) ); p.drawText( rectText, flags, ti.strCaption ); }
void TimelineBar::paintEvent(QPaintEvent *e) { QPainter p(viewport()); p.setFont(font()); p.setRenderHint(QPainter::TextAntialiasing); // draw boundaries and background { QRectF r = viewport()->rect(); p.fillRect(r, palette().brush(QPalette::Window)); r = r.marginsRemoved(QMargins(borderWidth + margin, borderWidth + margin, borderWidth + margin, borderWidth + margin)); p.fillRect(r, palette().brush(QPalette::Base)); p.drawRect(r); } QTextOption to; to.setWrapMode(QTextOption::NoWrap); to.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); QFontMetrics fm = p.fontMetrics(); { QRectF titleRect = m_eidAxisRect; titleRect.setLeft(titleRect.left() - m_titleWidth); titleRect.setWidth(m_titleWidth); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); // add an extra margin for the text p.drawText(titleRect.marginsRemoved(QMarginsF(margin, 0, 0, 0)), eidAxisTitle, to); titleRect.setLeft(titleRect.left() - margin); titleRect.setTop(titleRect.top() - margin); p.drawLine(titleRect.bottomLeft(), titleRect.bottomRight()); p.drawLine(titleRect.topRight(), titleRect.bottomRight()); } QRectF eidAxisRect = m_eidAxisRect; p.drawLine(eidAxisRect.bottomLeft(), eidAxisRect.bottomRight() + QPointF(margin, 0)); p.drawLine(m_highlightingRect.topLeft(), m_highlightingRect.topRight()); if(m_Draws.isEmpty()) return; eidAxisRect.setLeft(m_eidAxisRect.left() + m_pan); uint32_t maxEID = m_Draws.isEmpty() ? 0 : m_Draws.back(); to.setAlignment(Qt::AlignCenter | Qt::AlignVCenter); p.setFont(Formatter::PreferredFont()); QRectF hoverRect = eidAxisRect; // clip labels to the visible section p.setClipRect(m_eidAxisRect.marginsAdded(QMargins(0, margin, margin, 0))); // draw where we're hovering { QPoint pos = viewport()->mapFromGlobal(QCursor::pos()); if(m_dataArea.contains(pos)) { uint32_t hoverEID = eventAt(pos.x()); hoverRect.setLeft(offsetOf(hoverEID)); hoverRect.setWidth(m_eidAxisLabelWidth); // recentre hoverRect.moveLeft(hoverRect.left() - m_eidAxisLabelWidth / 2 + m_eidWidth / 2); QColor backCol = palette().color(QPalette::Base); if(getLuminance(backCol) < 0.2f) backCol = backCol.lighter(120); else backCol = backCol.darker(120); QRectF backRect = hoverRect.marginsAdded(QMargins(0, margin - borderWidth, 0, 0)); backRect.setLeft(qMax(backRect.left(), m_eidAxisRect.left() + 1)); p.fillRect(backRect, backCol); p.drawText(hoverRect, QString::number(hoverEID), to); // re-add the top margin so the lines match up with the border around the EID axis hoverRect = hoverRect.marginsAdded(QMargins(0, margin, 0, 0)); if(hoverRect.left() >= m_eidAxisRect.left()) p.drawLine(hoverRect.topLeft(), hoverRect.bottomLeft()); p.drawLine(hoverRect.topRight(), hoverRect.bottomRight()); // shrink the rect a bit for clipping against labels below hoverRect.setX(qRound(hoverRect.x() + 0.5)); hoverRect.setWidth(int(hoverRect.width())); } else { hoverRect = QRectF(); } } QRectF labelRect = eidAxisRect; labelRect.setWidth(m_eidAxisLabelWidth); // iterate through the EIDs from 0, starting from possible a negative offset if the user has // panned to the right. for(uint32_t i = 0; i <= maxEID; i += m_eidAxisLabelStep) { labelRect.moveLeft(offsetOf(i) - labelRect.width() / 2 + m_eidWidth / 2); // check if this label is visible at all, but don't draw labels that intersect with the hovered // number if(labelRect.right() >= 0 && !labelRect.intersects(hoverRect)) p.drawText(labelRect, QString::number(i), to); // check if labelRect is off the edge of the screen if(labelRect.left() >= m_eidAxisRect.right()) break; } // stop clipping p.setClipRect(viewport()->rect()); // clip the markers p.setClipRect(m_markerRect); { QPen pen = p.pen(); paintMarkers(p, m_RootMarkers, m_RootDraws, m_markerRect); p.setPen(pen); } // stop clipping p.setClipRect(viewport()->rect()); QRectF currentRect = eidAxisRect; // draw the current label and line { uint32_t curEID = m_Ctx.CurEvent(); currentRect.setLeft(offsetOf(curEID)); currentRect.setWidth( qMax(m_eidAxisLabelWidth, m_eidAxisLabelTextWidth + dataBarHeight + margin * 2)); // recentre currentRect.moveLeft(currentRect.left() - currentRect.width() / 2 + m_eidWidth / 2); // remember where the middle would have been, without clamping qreal realMiddle = currentRect.center().x(); // clamp the position from the left or right side if(currentRect.left() < eidAxisRect.left()) currentRect.moveLeft(eidAxisRect.left()); else if(currentRect.right() > eidAxisRect.right()) currentRect.moveRight(eidAxisRect.right()); // re-add the top margin so the lines match up with the border around the EID axis QRectF currentBackRect = currentRect.marginsAdded(QMargins(0, margin, 0, 0)); p.fillRect(currentBackRect, palette().brush(QPalette::Base)); p.drawRect(currentBackRect); // draw the 'current marker' pixmap const QPixmap &px = Pixmaps::flag_green(devicePixelRatio()); p.drawPixmap(currentRect.topLeft() + QPointF(margin, 1), px, px.rect()); // move to where the text should be and draw it currentRect.setLeft(currentRect.left() + margin * 2 + dataBarHeight); p.drawText(currentRect, QString::number(curEID), to); // draw a line from the bottom of the shadow downwards QPointF currentTop = currentRect.center(); currentTop.setX(int(qBound(eidAxisRect.left(), realMiddle, eidAxisRect.right() - 2.0)) + 0.5); currentTop.setY(currentRect.bottom()); QPointF currentBottom = currentTop; currentBottom.setY(m_markerRect.bottom()); p.drawLine(currentTop, currentBottom); } to.setAlignment(Qt::AlignLeft | Qt::AlignTop); if(!m_UsageTarget.isEmpty() || !m_HistoryTarget.isEmpty()) { p.setRenderHint(QPainter::Antialiasing); QRectF highlightLabel = m_highlightingRect.marginsRemoved(uniformMargins(margin)); highlightLabel.setX(highlightLabel.x() + margin); QString text; if(!m_HistoryTarget.isEmpty()) text = tr("Pixel history for %1").arg(m_HistoryTarget); else text = tr("Usage for %1:").arg(m_UsageTarget); p.drawText(highlightLabel, text, to); const int triRadius = fm.averageCharWidth(); const int triHeight = fm.ascent(); QPainterPath triangle; triangle.addPolygon( QPolygonF({QPoint(0, triHeight), QPoint(triRadius * 2, triHeight), QPoint(triRadius, 0)})); triangle.closeSubpath(); enum { ReadUsage, WriteUsage, ReadWriteUsage, ClearUsage, BarrierUsage, HistoryPassed, HistoryFailed, UsageCount, }; const QColor colors[UsageCount] = { // read QColor(Qt::red), // write QColor(Qt::green), // read/write QColor(Qt::yellow), // clear QColor(Qt::blue), // barrier QColor(Qt::magenta), // pass QColor(Qt::green), // fail QColor(Qt::red), }; // draw the key if(m_HistoryTarget.isEmpty()) { // advance past the first text to draw the key highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); text = lit(" Reads ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); QPainterPath path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ReadUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" ), Writes ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[WriteUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" ), Read/Write ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ReadWriteUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); if(m_Ctx.CurPipelineState().SupportsBarriers()) { text = lit(" ) Barriers ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[BarrierUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); } text = lit(" ), and Clears ( "); p.drawText(highlightLabel, text, to); highlightLabel.setLeft(highlightLabel.left() + fm.width(text)); path = triangle.translated(aliasAlign(highlightLabel.topLeft())); p.fillPath(path, colors[ClearUsage]); p.drawPath(path); highlightLabel.setLeft(highlightLabel.left() + triRadius * 2); text = lit(" )"); p.drawText(highlightLabel, text, to); } PipRanges pipranges[UsageCount]; QRectF pipsRect = m_highlightingRect.marginsRemoved(uniformMargins(margin)); pipsRect.setX(pipsRect.x() + margin + m_titleWidth); pipsRect.setHeight(triHeight + margin); pipsRect.moveBottom(m_highlightingRect.bottom()); p.setClipRect(pipsRect); qreal leftClip = -triRadius * 2.0; qreal rightClip = pipsRect.width() + triRadius * 10.0; if(!m_HistoryEvents.isEmpty()) { for(const PixelModification &mod : m_HistoryEvents) { qreal pos = offsetOf(mod.eventId) + m_eidWidth / 2 - triRadius; if(pos < leftClip || pos > rightClip) continue; if(mod.Passed()) pipranges[HistoryPassed].push(pos, triRadius); else pipranges[HistoryFailed].push(pos, triRadius); } } else { for(const EventUsage &use : m_UsageEvents) { qreal pos = offsetOf(use.eventId) + m_eidWidth / 2 - triRadius; if(pos < leftClip || pos > rightClip) continue; if(((int)use.usage >= (int)ResourceUsage::VS_RWResource && (int)use.usage <= (int)ResourceUsage::All_RWResource) || use.usage == ResourceUsage::GenMips || use.usage == ResourceUsage::Copy || use.usage == ResourceUsage::Resolve) { pipranges[ReadWriteUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::StreamOut || use.usage == ResourceUsage::ResolveDst || use.usage == ResourceUsage::ColorTarget || use.usage == ResourceUsage::DepthStencilTarget || use.usage == ResourceUsage::CopyDst) { pipranges[WriteUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::Clear) { pipranges[ClearUsage].push(pos, triRadius); } else if(use.usage == ResourceUsage::Barrier) { pipranges[BarrierUsage].push(pos, triRadius); } else { pipranges[ReadUsage].push(pos, triRadius); } } } for(int i = 0; i < UsageCount; i++) { QPainterPath path = pipranges[i].makePath(triRadius, triHeight, pipsRect.y()); if(!path.isEmpty()) { p.drawPath(path); p.fillPath(path, colors[i]); } } } else { QRectF highlightLabel = m_highlightingRect; highlightLabel = highlightLabel.marginsRemoved(uniformMargins(margin)); highlightLabel.setX(highlightLabel.x() + margin); p.drawText(highlightLabel, tr("No resource selected for highlighting."), to); } }
// if painter is nullptr, the method calculate the bounding rectangle of the text and save it to textRect void FolderItemDelegate::drawText(QPainter* painter, QStyleOptionViewItemV4& opt, QRectF& textRect) const { QTextLayout layout(opt.text, opt.font); QTextOption textOption; textOption.setAlignment(opt.displayAlignment); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); textOption.setTextDirection(opt.direction); layout.setTextOption(textOption); qreal height = 0; qreal width = 0; int visibleLines = 0; layout.beginLayout(); QString elidedText; for(;;) { QTextLine line = layout.createLine(); if(!line.isValid()) break; line.setLineWidth(textRect.width()); height += opt.fontMetrics.leading(); line.setPosition(QPointF(0, height)); if((height + line.height() + textRect.y()) > textRect.bottom()) { // if part of this line falls outside the textRect, ignore it and quit. QTextLine lastLine = layout.lineAt(visibleLines - 1); elidedText = opt.text.mid(lastLine.textStart()); elidedText = opt.fontMetrics.elidedText(elidedText, opt.textElideMode, textRect.width()); if(visibleLines == 1) // this is the only visible line width = textRect.width(); break; } height += line.height(); width = qMax(width, line.naturalTextWidth()); ++ visibleLines; } layout.endLayout(); // draw background for selected item QRectF boundRect = layout.boundingRect(); //qDebug() << "bound rect: " << boundRect << "width: " << width; boundRect.setWidth(width); boundRect.moveTo(textRect.x() + (textRect.width() - width)/2, textRect.y()); if(!painter) { // no painter, calculate the bounding rect only textRect = boundRect; return; } QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if(opt.state & QStyle::State_Selected) { painter->fillRect(boundRect, opt.palette.highlight()); painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else painter->setPen(opt.palette.color(cg, QPalette::Text)); // draw text for(int i = 0; i < visibleLines; ++i) { QTextLine line = layout.lineAt(i); if(i == (visibleLines - 1) && !elidedText.isEmpty()) { // the last line, draw elided text QPointF pos(textRect.x() + line.position().x(), textRect.y() + line.y() + line.ascent()); painter->drawText(pos, elidedText); } else { line.draw(painter, textRect.topLeft()); } } if(opt.state & QStyle::State_HasFocus) { // draw focus rect QStyleOptionFocusRect o; o.QStyleOption::operator=(opt); o.rect = boundRect.toRect(); // subElementRect(SE_ItemViewItemFocusRect, vopt, widget); o.state |= QStyle::State_KeyboardFocusChange; o.state |= QStyle::State_Item; QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled) ? QPalette::Normal : QPalette::Disabled; o.backgroundColor = opt.palette.color(cg, (opt.state & QStyle::State_Selected) ? QPalette::Highlight : QPalette::Window); if (const QWidget* widget = opt.widget) { QStyle* style = widget->style() ? widget->style() : qApp->style(); style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, widget); } } }
void TimelineBar::paintMarkers(QPainter &p, const QVector<Marker> &markers, const QVector<uint32_t> &draws, QRectF markerRect) { if(markers.isEmpty() && draws.isEmpty()) return; QTextOption to; to.setWrapMode(QTextOption::NoWrap); to.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); QFontMetrics fm(Formatter::PreferredFont()); // store a reference of what a completely elided string looks like QString tooshort = fm.elidedText(lit("asd"), Qt::ElideRight, fm.height()); for(const Marker &m : markers) { QRectF r = markerRect; r.setLeft(qMax(m_dataArea.left() + borderWidth * 3, offsetOf(m.eidStart))); r.setRight(qMin(m_dataArea.right() - borderWidth, offsetOf(m.eidEnd + 1))); r.setHeight(fm.height() + borderWidth * 2); if(r.width() <= borderWidth * 2) continue; QColor backColor = m.color; if(r.contains(m_lastPos)) backColor.setAlpha(150); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); p.fillRect(r, QBrush(backColor)); p.drawRect(r); p.setPen(QPen(QBrush(contrastingColor(backColor, palette().color(QPalette::Text))), 1.0)); r.setLeft(r.left() + margin); int plusWidth = fm.width(QLatin1Char('+')); if(r.width() > plusWidth) { QRectF plusRect = r; plusRect.setWidth(plusWidth); QTextOption plusOption = to; plusOption.setAlignment(Qt::AlignCenter | Qt::AlignVCenter); p.drawText(plusRect, m.expanded ? lit("-") : lit("+"), plusOption); r.setLeft(r.left() + plusWidth + margin); } QString elided = fm.elidedText(m.name, Qt::ElideRight, r.width()); // if everything was elided, just omit the title entirely if(elided == tooshort) elided = QString(); r.setLeft(qRound(r.left() + margin)); p.drawText(r, elided, to); if(m.expanded) { QRectF childRect = r; childRect.setTop(r.bottom() + borderWidth * 2); childRect.setBottom(markerRect.bottom()); paintMarkers(p, m.children, m.draws, childRect); } } p.setRenderHint(QPainter::Antialiasing); for(uint32_t d : draws) { QRectF r = markerRect; r.setLeft(qMax(m_dataArea.left() + borderWidth * 3, offsetOf(d))); r.setRight(qMin(m_dataArea.right() - borderWidth, offsetOf(d + 1))); r.setHeight(fm.height() + borderWidth * 2); QPainterPath path; path.addRoundedRect(r, 5, 5); p.setPen(QPen(palette().brush(QPalette::Text), 1.0)); p.fillPath(path, d == m_Ctx.CurEvent() ? Qt::green : Qt::blue); p.drawPath(path); } p.setRenderHint(QPainter::Antialiasing, false); }
void QgsComposerLegend::paint( QPainter *painter, const QStyleOptionGraphicsItem *itemStyle, QWidget *pWidget ) { Q_UNUSED( itemStyle ); Q_UNUSED( pWidget ); if ( !painter ) return; if ( !shouldDrawItem() ) { return; } if ( mFilterAskedForUpdate ) { mFilterAskedForUpdate = false; doUpdateFilterByMap(); } int dpi = painter->device()->logicalDpiX(); double dotsPerMM = dpi / 25.4; if ( mComposition ) { mSettings.setUseAdvancedEffects( mComposition->useAdvancedEffects() ); mSettings.setDpi( dpi ); } if ( mComposerMap ) { mSettings.setMmPerMapUnit( mComposerMap->mapUnitsToMM() ); // use a temporary QgsMapSettings to find out real map scale QSizeF mapSizePixels = QSizeF( mComposerMap->rect().width() * dotsPerMM, mComposerMap->rect().height() * dotsPerMM ); QgsRectangle mapExtent = *mComposerMap->currentMapExtent(); QgsMapSettings ms = mComposerMap->mapSettings( mapExtent, mapSizePixels, dpi ); mSettings.setMapScale( ms.scale() ); } mInitialMapScaleCalculated = true; QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings ); legendRenderer.setLegendSize( mForceResize && mSizeToContents ? QSize() : rect().size() ); //adjust box if width or height is too small if ( mSizeToContents ) { QSizeF size = legendRenderer.minimumSize(); if ( mForceResize ) { mForceResize = false; //set new rect, respecting position mode and data defined size/position QRectF targetRect = QRectF( pos().x(), pos().y(), size.width(), size.height() ); setSceneRect( evalItemRect( targetRect, true ) ); } else if ( size.height() > rect().height() || size.width() > rect().width() ) { //need to resize box QRectF targetRect = QRectF( pos().x(), pos().y(), rect().width(), rect().height() ); if ( size.height() > targetRect.height() ) targetRect.setHeight( size.height() ); if ( size.width() > rect().width() ) targetRect.setWidth( size.width() ); //set new rect, respecting position mode and data defined size/position setSceneRect( evalItemRect( targetRect, true ) ); } } drawBackground( painter ); painter->save(); //antialiasing on painter->setRenderHint( QPainter::Antialiasing, true ); painter->setPen( QPen( QColor( 0, 0, 0 ) ) ); if ( !mSizeToContents ) { // set a clip region to crop out parts of legend which don't fit QRectF thisPaintRect = QRectF( 0, 0, rect().width(), rect().height() ); painter->setClipRect( thisPaintRect ); } legendRenderer.drawLegend( painter ); painter->restore(); //draw frame and selection boxes if necessary drawFrame( painter ); if ( isSelected() ) { drawSelectionBoxes( painter ); } }
QVariant HandleItem::itemChange( GraphicsItemChange change, const QVariant &data ) { if ( change == ItemPositionChange && m_pressed ) { QPointF newData = data.toPointF(); QRectF newRect = m_item->rect(); QPointF movement = newData - pos(); switch ( m_role ) { case RightHandle: { // Prevent the rectangle from collapsing. if ( newRect.width() + movement.x() <= MinSize ) { newRect.setWidth(MinSize); m_item->setRect(newRect); newData.setX(m_item->boundingRect().x() + MinSize/2); newData.setY(pos().y()); } else { // Snap the movement to the X direction newData.setY(m_item->rect().y() + m_item->rect().height() / 2 - HandleRadius); // Resize the rectangle newRect.setRight(m_item->rect().right() + movement.x()); m_item->setRect(newRect); } break; } case LeftHandle: { // Prevent the rectangle from collapsing if ( newRect.width() - movement.x() <= MinSize ) { newRect.setLeft(newRect.right() - MinSize); //float oldLeft = m_item->rect().left(); //newRect.setWidth(MinSize); //newRect.setLeft(oldLeft); m_item->setRect(newRect); newData.setX(m_item->boundingRect().x() - MinSize / 2); newData.setY(pos().y()); } else { // Snap the movement to the X direction newData.setY(m_item->rect().y() + m_item->rect().height() / 2 - HandleRadius); // Resize the rectangle newRect.setLeft(m_item->rect().left() + movement.x()); m_item->setRect(newRect); } break; } case TopHandle: { // Prevent the rectangle from collapsing. if ( newRect.height() - movement.y() <= MinSize ) { newRect.setTop(newRect.bottom() - MinSize); //newRect.setHeight(MinSize); m_item->setRect(newRect); newData.setX(pos().x()); newData.setY(m_item->boundingRect().y() - boundingRect().height() / 2); // + m_item->boundingRect().height()); } else { // Snap the movement to the Y direction newData.setX(m_item->rect().x() + m_item->rect().width() / 2 - HandleRadius); // Resize the rectangle newRect.setTop(m_item->rect().top() + movement.y()); m_item->setRect(newRect); } break; } case BottomHandle: { // Prevent the rectangle from collapsing. if ( newRect.height() + movement.y() <= MinSize ) { newRect.setBottom(newRect.top() + MinSize); m_item->setRect(newRect); newData.setX(pos().x()); newData.setY(m_item->boundingRect().y() + boundingRect().height() / 2); } else { // Snap the movement to the Y direction newData.setX(m_item->rect().x() + m_item->rect().width() / 2 - HandleRadius); // Resize the rectangle newRect.setBottom(m_item->rect().bottom() + movement.y()); m_item->setRect(newRect); } break; } case CenterHandle: { //m_item->translate(movement.x(), movement.y()); QRectF rect = m_item->rect(); rect.setX(rect.x() + movement.x()); rect.setY(rect.y() + movement.y()); rect.setWidth(rect.width() + movement.x()); rect.setHeight(rect.height() + movement.y()); m_item->setRect(rect); break; } } // end switch emit Changed(); return QGraphicsItem::itemChange( change, newData ); } // end if pressed return QGraphicsItem::itemChange( change, data ); }
/*********************************************************************** *Funtion : Move the draged handle to mouse point *Return : DRAG_CROSS_TYPE_E cross type *Parameter: integer draged handle id, QPointF mouse local point, scene bonding rect **********************************************************************/ QRectF SamDrawItemBase::moveHandleTo(int iDragHandle, QPointF qpLocal, QRectF &qrcBondingRect, bool bFoursquare) { QRectF qrcPosition; //qrcPosition = this->sceneBoundingRect(); qrcPosition = qrcBondingRect; switch (iDragHandle) { case HANDLE_LEFT_TOP: qrcPosition.setLeft(qpLocal.x()); qrcPosition.setTop(qpLocal.y()); if (bFoursquare) { qrcPosition.setLeft(qpLocal.x()); qrcPosition.setTop(qpLocal.y()); if (qrcPosition.height() > qrcPosition.width()) { qrcPosition.setLeft(qrcPosition.right() - qrcPosition.height()); } else if (qrcPosition.height() < qrcPosition.width()) { qrcPosition.setTop(qrcPosition.bottom() - qrcPosition.width()); } } break; case HANDLE_CENTER_TOP: qrcPosition.setTop(qpLocal.y()); if (bFoursquare) { qrcPosition.setWidth(qrcPosition.height()); } break; case HANDLE_RIGHT_TOP: qrcPosition.setRight(qpLocal.x()); qrcPosition.setTop(qpLocal.y()); if (bFoursquare) { if (qrcPosition.height() > qrcPosition.width()) { qrcPosition.setWidth(qrcPosition.height()); } else if (qrcPosition.height() < qrcPosition.width()) { qrcPosition.setTop(qrcPosition.bottom() - qrcPosition.width()); } } break; case HANDLE_RIGHT_CENTER: qrcPosition.setRight(qpLocal.x()); if (bFoursquare) { qrcPosition.setHeight(qrcPosition.width()); } break; case HANDLE_RIGHT_BOTTOM: qrcPosition.setRight(qpLocal.x()); qrcPosition.setBottom(qpLocal.y()); if (bFoursquare) { if (qrcPosition.height() > qrcPosition.width()) { qrcPosition.setWidth(qrcPosition.height()); } else if (qrcPosition.height() < qrcPosition.width()) { qrcPosition.setHeight(qrcPosition.width()); } } break; case HANDLE_CENTER_BOTTOM: qrcPosition.setBottom(qpLocal.y()); if (bFoursquare) { qrcPosition.setWidth(qrcPosition.height()); } break; case HANDLE_LEFT_BOTTOM: qrcPosition.setLeft(qpLocal.x()); qrcPosition.setBottom(qpLocal.y()); if (bFoursquare) { if (qrcPosition.height() > qrcPosition.width()) { qrcPosition.setLeft(qrcPosition.right() - qrcPosition.height()); } else if (qrcPosition.height() < qrcPosition.width()) { qrcPosition.setHeight(qrcPosition.width()); } } break; case HANDLE_LEFT_CENTER: qrcPosition.setLeft(qpLocal.x()); if (bFoursquare) { qrcPosition.setHeight(qrcPosition.width()); } break; default: return qrcPosition; } return qrcPosition; }
void vogleditor_QTimelineView::drawTimelineItem(QPainter* painter, vogleditor_timelineItem *pItem, int height, float& minimumOffset) { float duration = pItem->getDuration(); if (duration < 0) { return; } painter->save(); if (pItem->isMarker()) { painter->setBrush(m_triangleBrush); painter->setPen(m_trianglePen); float offset = scalePositionHorizontally(pItem->getBeginTime()); painter->drawLine(QLineF(offset, -height, offset, height)); } else { // only draw if the item will extend beyond the minimum offset float leftOffset = scalePositionHorizontally(pItem->getBeginTime()); float scaledWidth = scaleDurationHorizontally(duration); if (minimumOffset < leftOffset + scaledWidth) { float durationRatio = duration / m_maxItemDuration; int intensity = std::min(255, (int)(durationRatio * 255.0f)); // painter->setBrush(*(pItem->getBrush())); QColor color(intensity, 255-intensity, 0); painter->setBrush(QBrush(color)); painter->setPen(color); // Clamp the item so that it is 1 pixel wide. // This is intentionally being done before updating the minimum offset // so that small items after the current item will not be drawn if (scaledWidth < 1) { scaledWidth = 1; } // update minimum offset minimumOffset = leftOffset + scaledWidth; // draw the colored box that represents this item QRectF rect; rect.setLeft(leftOffset); rect.setTop(-height/2); rect.setWidth(scaledWidth); rect.setHeight(height); painter->drawRect(rect); // now draw all children int numChildren = pItem->childCount(); for (int c = 0; c < numChildren; c++) { drawTimelineItem(painter, pItem->child(c), height-1, minimumOffset); } } } painter->restore(); }