/*! Transform a rectangle from scale to paint coordinates \param xMap X map \param yMap Y map \param rect Rectangle in scale coordinates \return Rectangle in paint coordinates \sa invTransform() */ QRectF QwtScaleMap::transform( const QwtScaleMap &xMap, const QwtScaleMap &yMap, const QRectF &rect ) { double x1 = xMap.transform( rect.left() ); double x2 = xMap.transform( rect.right() ); double y1 = yMap.transform( rect.top() ); double y2 = yMap.transform( rect.bottom() ); if ( x2 < x1 ) qSwap( x1, x2 ); if ( y2 < y1 ) qSwap( y1, y2 ); if ( qwtFuzzyCompare( x1, 0.0, x2 - x1 ) == 0 ) x1 = 0.0; if ( qwtFuzzyCompare( x2, 0.0, x2 - x1 ) == 0 ) x2 = 0.0; if ( qwtFuzzyCompare( y1, 0.0, y2 - y1 ) == 0 ) y1 = 0.0; if ( qwtFuzzyCompare( y2, 0.0, y2 - y1 ) == 0 ) y2 = 0.0; return QRectF( x1, y1, x2 - x1 + 1, y2 - y1 + 1 ); }
KoShapeDistributeCommand::KoShapeDistributeCommand(const QList<KoShape*> &shapes, Distribute distribute, const QRectF &boundingRect, KUndo2Command *parent) : KUndo2Command(parent), d(new Private()) { d->distribute = distribute; QMap<qreal, KoShape*> sortedPos; QRectF bRect; qreal extent = 0.0; // sort by position and calculate sum of objects widht/height foreach(KoShape *shape, shapes) { bRect = shape->boundingRect(); switch (d->distribute) { case HorizontalCenterDistribution: sortedPos[bRect.center().x()] = shape; break; case HorizontalGapsDistribution: case HorizontalLeftDistribution: sortedPos[bRect.left()] = shape; extent += bRect.width(); break; case HorizontalRightDistribution: sortedPos[bRect.right()] = shape; break; case VerticalCenterDistribution: sortedPos[bRect.center().y()] = shape; break; case VerticalGapsDistribution: case VerticalBottomDistribution: sortedPos[bRect.bottom()] = shape; extent += bRect.height(); break; case VerticalTopDistribution: sortedPos[bRect.top()] = shape; break; } }
void datamatrixGeometry(QString &inFormat, const QRectF &inQrect,DmtxImage *inImg, qreal *outXo, qreal *outYo, qreal *outPas) { *outPas = std::min(inQrect.width()/inImg->width, inQrect.height()/inImg->height); *outYo = inQrect.bottom(); //alignement left if(inFormat == "L") { *outXo = inQrect.left(); } //alignement Center if(inFormat == "C") { qreal Xc = (inQrect.left() + inQrect.right()) / 2; *outXo = Xc - (((qreal)inImg->width) * (*outPas)); } //alignement Rigth if(inFormat == "R") { *outXo = inQrect.right() - (*outPas * inImg->width); } }
//! [6] void GraphWidget::drawBackground(QPainter *painter, const QRectF &rect) { Q_UNUSED(rect); // Shadow QRectF sceneRect = this->sceneRect(); QRectF rightShadow(sceneRect.right(), sceneRect.top() + 5, 5, sceneRect.height()); QRectF bottomShadow(sceneRect.left() + 5, sceneRect.bottom(), sceneRect.width(), 5); if (rightShadow.intersects(rect) || rightShadow.contains(rect)) painter->fillRect(rightShadow, Qt::darkGray); if (bottomShadow.intersects(rect) || bottomShadow.contains(rect)) painter->fillRect(bottomShadow, Qt::darkGray); // Fill QLinearGradient gradient(sceneRect.topLeft(), sceneRect.bottomRight()); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, Qt::lightGray); painter->fillRect(rect.intersect(sceneRect), gradient); painter->setBrush(Qt::NoBrush); painter->drawRect(sceneRect); // Text QRectF textRect(sceneRect.left() + 4, sceneRect.top() + 4, sceneRect.width() - 4, sceneRect.height() - 4); QString message(tr("Click and drag the nodes around, and zoom with the mouse " "wheel or the '+' and '-' keys")); QFont font = painter->font(); font.setBold(true); font.setPointSize(14); painter->setFont(font); painter->setPen(Qt::lightGray); painter->drawText(textRect.translated(2, 2), message); painter->setPen(Qt::black); painter->drawText(textRect, message); }
void DateTimeGrid::paintRowGrid( QPainter* painter, const QRectF& /*sceneRect*/, const QRectF& exposedRect, AbstractRowController* rowController, QWidget* /*widget*/ ) { if ( rowController && rowSeparators() ) { // First draw the rows QPen pen = painter->pen(); pen.setBrush( QApplication::palette().dark() ); pen.setStyle( Qt::DashLine ); painter->setPen( pen ); QModelIndex idx = rowController->indexAt( qRound( exposedRect.top() ) ); qreal y = 0; while ( y < exposedRect.bottom() && idx.isValid() ) { const Span s = rowController->rowGeometry( idx ); y = s.start()+s.length(); //painter->drawLine( QPointF( sceneRect.left(), y ), QPointF( sceneRect.right(), y ) ); // Is alternating background better? if ( idx.row()%2 ) painter->fillRect( QRectF( exposedRect.x(), s.start(), exposedRect.width(), s.length() ), QApplication::palette().alternateBase() ); idx = rowController->indexBelow( idx ); } } }
BasepointPixmap OverlayTextLine::createPixmap(QColor col) { if (qsText.isEmpty()) { return BasepointPixmap(); } QRectF qr; if (qpp.isEmpty()) { qpp.addText(0.0f, fAscent, qfFont, qsText); qr = qpp.controlPointRect(); // fit into (0,0)-based coordinates fXCorrection = 0.0f; fYCorrection = 0.0f; if (qr.left() < fEdge) { fXCorrection = fEdge - static_cast<float>(qr.left()); } if (qr.top() < fEdge) { fYCorrection = fEdge - static_cast<float>(qr.top()); } QMatrix correction; correction.translate(fXCorrection, fYCorrection); qpp = correction.map(qpp); } qr = qpp.controlPointRect(); return render( iroundf(qr.right() + 2.0f*fEdge + 0.5f), iroundf(qr.bottom() + 2.0f*fEdge + 0.5f), col, QPoint(iroundf(fXCorrection + 0.5f), iroundf(fYCorrection + fAscent + 0.5f)) ); }
void DynamicController::drawGate(QSGNode * rootNode) { //Update knobs if (!this->simple()) { QObject * gateKnob = knobs[0]; gateKnob->setProperty("x", graphToNodeX(_tempModel["gatex"])); gateKnob->setProperty("y", graphToNodeY(_tempModel["gatey"])); } QSGGeometryNode * lineNode = new QSGGeometryNode(); QSGGeometry * lineGeom = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), (3)); QSGFlatColorMaterial *material = new QSGFlatColorMaterial; material->setColor(this->curveColor()); material->setFlag(QSGMaterial::Blending); lineNode->setMaterial(material); lineNode->setFlag(QSGNode::OwnsGeometry); lineNode->setFlag(QSGNode::OwnedByParent); lineNode->setFlag(QSGNode::OwnsMaterial); lineGeom->setDrawingMode(GL_LINE_STRIP); glLineWidth(2.0f); QSGGeometry::Point2D* points = lineGeom->vertexDataAsPoint2D(); QRectF bounds = boundingRect(); points->set(graphToNodeX(_tempModel["gatex"]), bounds.bottom()); points++; points->set(graphToNodeX(_tempModel["gatex"]), graphToNodeX(_tempModel["gatey"])); points++; points->set(bounds.right(), bounds.top()); points++; lineNode->setGeometry(lineGeom); rootNode->appendChildNode(lineNode); }
/*! Draw a column for a sample in Columns style(). When a symbol() has been set the symbol is used otherwise the column is displayed as plain rectangle using pen() and brush(). \param painter Painter \param rect Rectangle where to paint the column in paint device coordinates \param sample Sample to be displayed \note In applications, where different intervals need to be displayed in a different way ( f.e different colors or even using differnt symbols) it is recommended to overload drawColumn(). */ void QwtPlotHistogram::drawColumn( QPainter *painter, const QwtColumnRect &rect, const QwtIntervalSample &sample ) const { Q_UNUSED( sample ); if ( d_data->symbol && ( d_data->symbol->style() != QwtColumnSymbol::NoStyle ) ) { d_data->symbol->draw( painter, rect ); } else { QRectF r = rect.toRect(); if ( QwtPainter::roundingAlignment( painter ) ) { r.setLeft( qRound( r.left() ) ); r.setRight( qRound( r.right() ) ); r.setTop( qRound( r.top() ) ); r.setBottom( qRound( r.bottom() ) ); } QwtPainter::drawRect( painter, r ); } }
void RefactorOverlay::paintMarker(const RefactorMarker& marker, QPainter *painter, const QRect &clip) { QPointF offset = m_editor->contentOffset(); QRectF geometry = m_editor->blockBoundingGeometry(marker.cursor.block()).translated(offset); if (geometry.top() > clip.bottom() + 10 || geometry.bottom() < clip.top() - 10) return; // marker not visible QTextCursor cursor = marker.cursor; QRect r = m_editor->cursorRect(cursor); QIcon icon = marker.icon; if (icon.isNull()) icon = m_icon; QSize sz = icon.actualSize(QSize(m_editor->fontMetrics().width(QLatin1Char(' '))+2, r.height())); int x = r.right(); marker.rect = QRect(x, r.top(), sz.width(), sz.height()); icon.paint(painter, marker.rect); m_maxWidth = qMax((qreal)m_maxWidth, x + sz.width() - offset.x()); }
void QSanCommandProgressBar::paintEvent(QPaintEvent *e) { m_mutex.lock(); int val = this->m_val; int max = this->m_max; m_mutex.unlock(); int width = this->width(); int height = this->height(); QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); if (orientation() == Qt::Vertical) { painter.translate(0, height); qSwap(width, height); painter.rotate(-90); } painter.drawPixmap(0, 0, width, height, m_progBg); double percent = 1 - (double)val / (double)max; QRectF rect = QRectF(0, 0, percent * width, height); //ÒÔrectµÄÓÒ±ßΪÖÐÖᣬ7Ϊ°ë¾¶»Ò»¸öÍÖÔ² QRectF ellipseRect; ellipseRect.setTopLeft(QPointF(rect.right() - 7, rect.top())); ellipseRect.setBottomRight(QPointF(rect.right() + 7, rect.bottom())); QPainterPath rectPath; QPainterPath ellipsePath; rectPath.addRect(rect); ellipsePath.addEllipse(ellipseRect); QPainterPath polygonPath = rectPath.united(ellipsePath); painter.setClipPath(polygonPath); painter.drawPixmap(0, 0, width, height, m_prog); }
void OrthogonalRenderer::drawGrid(QPainter *painter, const QRectF &rect, QColor gridColor) const { const int tileWidth = map()->tileWidth(); const int tileHeight = map()->tileHeight(); if (tileWidth <= 0 || tileHeight <= 0) return; const int startX = qMax(0, (int) (rect.x() / tileWidth) * tileWidth); const int startY = qMax(0, (int) (rect.y() / tileHeight) * tileHeight); const int endX = qMin(qCeil(rect.right()), map()->width() * tileWidth + 1); const int endY = qMin(qCeil(rect.bottom()), map()->height() * tileHeight + 1); gridColor.setAlpha(128); QPen gridPen(gridColor); gridPen.setCosmetic(true); gridPen.setDashPattern(QVector<qreal>() << 2 << 2); if (startY < endY) { gridPen.setDashOffset(startY); painter->setPen(gridPen); for (int x = startX; x < endX; x += tileWidth) painter->drawLine(x, startY, x, endY - 1); } if (startX < endX) { gridPen.setDashOffset(startX); painter->setPen(gridPen); for (int y = startY; y < endY; y += tileHeight) painter->drawLine(startX, y, endX - 1, y); } }
qreal CompleteCoverageTask::performance(const QList<Position> &positions) { //This function is real slow. I should optimize it in the future. Quad trees or binning? //This function is also assuming flat earth... const qreal deltaDegrees = 0.001; const QRectF boundingBox = this->geoPoly().boundingRect(); QSet<QVector3D> toCheck; for (qreal x = boundingBox.left(); x < boundingBox.right(); x += deltaDegrees) { for (qreal y = boundingBox.top(); y < boundingBox.bottom(); y += deltaDegrees) { if (this->geoPoly().containsPoint(QPoint(x,y), Qt::OddEvenFill)) continue; toCheck.insert(Conversions::lla2xyz(y, x, 1500)); } } const qreal perHit = 500 / (qreal)toCheck.size(); qreal partials = 0.0; const qreal maxPartial = perHit / (positions.size() * toCheck.size()); QSet<QVector3D> hits; foreach(const Position & planePos, positions) { QVector3D pos = Conversions::lla2xyz(planePos); foreach(const QVector3D & sensorPoint, toCheck) { const qreal dist = (pos - sensorPoint).length(); if (dist < 10.0) hits.insert(sensorPoint); else if (dist < 20.0) partials += qMin<qreal>(maxPartial, 10*PathTask::normal(dist,20.0)); } }
/*! Calculate the geometry of the legend on the canvas \param canvasRect Geometry of the canvas \return Geometry of the legend */ QRect QwtPlotLegendItem::geometry( const QRectF &canvasRect ) const { QRect rect; rect.setSize( d_data->layout->sizeHint() ); int margin = d_data->borderDistance; if ( d_data->alignment & Qt::AlignHCenter ) { int x = qRound( canvasRect.center().x() ); rect.moveCenter( QPoint( x, rect.center().y() ) ); } else if ( d_data->alignment & Qt::AlignRight ) { rect.moveRight( qFloor( canvasRect.right() - margin ) ); } else { rect.moveLeft( qCeil( canvasRect.left() + margin ) ); } if ( d_data->alignment & Qt::AlignVCenter ) { int y = qRound( canvasRect.center().y() ); rect.moveCenter( QPoint( rect.center().x(), y ) ); } else if ( d_data->alignment & Qt::AlignBottom ) { rect.moveBottom( qFloor( canvasRect.bottom() - margin ) ); } else { rect.moveTop( qCeil( canvasRect.top() + margin ) ); } return rect; }
void InstrumentWindowMaskTab::shapeChanged() { if (!m_left) return; // check that everything is ok m_userEditing = false; // this prevents resetting shape proeprties by doubleChanged(...) QRectF rect = m_instrumentDisplay->getSurface()->getCurrentBoundingRect(); m_doubleManager->setValue(m_left,rect.left()); m_doubleManager->setValue(m_top,rect.top()); m_doubleManager->setValue(m_right,rect.right()); m_doubleManager->setValue(m_bottom,rect.bottom()); for(QMap<QtProperty *,QString>::iterator it = m_doublePropertyMap.begin(); it != m_doublePropertyMap.end(); ++it) { m_doubleManager->setValue(it.key(),m_instrumentDisplay->getSurface()->getCurrentDouble(it.value())); } for(QMap<QString,QtProperty *>::iterator it = m_pointPropertyMap.begin(); it != m_pointPropertyMap.end(); ++it) { QtProperty* prop = it.value(); QList<QtProperty*> subs = prop->subProperties(); if (subs.size() != 2) continue; QPointF p = m_instrumentDisplay->getSurface()->getCurrentPoint(it.key()); m_doubleManager->setValue(subs[0],p.x()); m_doubleManager->setValue(subs[1],p.y()); } m_userEditing = true; }
void PeopleApplication::repositionOverlays() { QRectF exposed = m_mainPage->exposedContentRect(); if (m_window->orientation() == M::Landscape) { m_sliderH->setPos(0, exposed.y()); m_sliderH->show(); m_sliderV->hide(); m_topSpacer->setPreferredHeight(m_sliderH->preferredHeight()); m_mainPage->layout()->setContentsMargins(0, 0, 0, 0); } else { int width = m_sliderV->preferredWidth(); m_sliderV->setPos(exposed.width() - width, exposed.y()); m_sliderV->setPreferredHeight(m_sliderH->preferredWidth()-exposed.y()); m_sliderH->hide(); m_sliderV->show(); m_topSpacer->setPreferredHeight(0); m_mainPage->layout()->setContentsMargins(0, 0, m_sliderV->preferredWidth(), 0); } if (m_searchWidget) m_searchWidget->setPos(0, exposed.bottom() - m_searchWidget->preferredHeight()); }
void TabSwitcherObject::paintEmbryo(QPainter *painter) { painter->setPen(Design::instance()->color(Design::TabLineColor)); painter->setBrush(Design::instance()->color(Design::TabNormalBgColor)); QRectF r = embryoRect(); QPainterPath path; double radius = Design::instance()->size(Design::TabRadius); path.moveTo(r.left(), r.top()+radius); path.arcTo(r.left(), r.top(), radius*2.0, radius*2.0, 180, -90); path.lineTo(r.left()+radius, r.top()); path.lineTo(r.right()-radius, r.top()); path.arcTo(r.right()-radius*2.0, r.top(), radius*2.0, radius*2.0, 90, -90); path.lineTo(r.right(), r.top()+radius); path.lineTo(r.right(), r.bottom()-radius); path.arcTo(r.right()-radius*2.0, r.bottom()-radius*2.0, radius*2.0, radius*2.0, 0, -90); path.lineTo(r.right()-radius, r.bottom()); path.lineTo(r.left()+radius, r.bottom()); path.arcTo(r.left(), r.bottom()-radius*2.0, radius*2.0, radius*2.0, -90, -90); path.lineTo(r.left(), r.bottom()-radius); path.closeSubpath(); painter->drawPath(path); }
/*! Draw a color bar into a rectangle \param painter Painter \param colorMap Color map \param interval Value range \param scaleMap Scale map \param orientation Orientation \param rect Traget rectangle */ void QwtPainter::drawColorBar( QPainter *painter, const QwtColorMap &colorMap, const QwtInterval &interval, const QwtScaleMap &scaleMap, Qt::Orientation orientation, const QRectF &rect ) { QVector<QRgb> colorTable; if ( colorMap.format() == QwtColorMap::Indexed ) colorTable = colorMap.colorTable( interval ); QColor c; const QRect devRect = rect.toAlignedRect(); /* We paint to a pixmap first to have something scalable for printing ( f.e. in a Pdf document ) */ QPixmap pixmap( devRect.size() ); QPainter pmPainter( &pixmap ); pmPainter.translate( -devRect.x(), -devRect.y() ); if ( orientation == Qt::Horizontal ) { QwtScaleMap sMap = scaleMap; sMap.setPaintInterval( rect.left(), rect.right() ); for ( int x = devRect.left(); x <= devRect.right(); x++ ) { const double value = sMap.invTransform( x ); if ( colorMap.format() == QwtColorMap::RGB ) c.setRgb( colorMap.rgb( interval, value ) ); else c = colorTable[colorMap.colorIndex( interval, value )]; pmPainter.setPen( c ); pmPainter.drawLine( x, devRect.top(), x, devRect.bottom() ); } } else // Vertical { QwtScaleMap sMap = scaleMap; sMap.setPaintInterval( rect.bottom(), rect.top() ); for ( int y = devRect.top(); y <= devRect.bottom(); y++ ) { const double value = sMap.invTransform( y ); if ( colorMap.format() == QwtColorMap::RGB ) c.setRgb( colorMap.rgb( interval, value ) ); else c = colorTable[colorMap.colorIndex( interval, value )]; pmPainter.setPen( c ); pmPainter.drawLine( devRect.left(), y, devRect.right(), y ); } } pmPainter.end(); drawPixmap( painter, rect, pixmap ); }
void GLUtils::fillRectangle( const QRectF& r ) { fillRectangle(r.left(), r.top(), r.right(), r.bottom()); }
QSGRenderer::ClipType QSGRenderer::updateStencilClip(const QSGClipNode *clip) { if (!clip) { glDisable(GL_STENCIL_TEST); glDisable(GL_SCISSOR_TEST); return NoClip; } bool stencilEnabled = false; bool scissorEnabled = false; glDisable(GL_SCISSOR_TEST); int clipDepth = 0; QRect clipRect; while (clip) { QMatrix4x4 m = m_current_projection_matrix; if (clip->matrix()) m *= *clip->matrix(); // TODO: Check for multisampling and pixel grid alignment. bool canUseScissor = clip->isRectangular() && qFuzzyIsNull(m(0, 1)) && qFuzzyIsNull(m(0, 2)) && qFuzzyIsNull(m(1, 0)) && qFuzzyIsNull(m(1, 2)); if (canUseScissor) { QRectF bbox = clip->clipRect(); qreal invW = 1 / m(3, 3); qreal fx1 = (bbox.left() * m(0, 0) + m(0, 3)) * invW; qreal fy1 = (bbox.bottom() * m(1, 1) + m(1, 3)) * invW; qreal fx2 = (bbox.right() * m(0, 0) + m(0, 3)) * invW; qreal fy2 = (bbox.top() * m(1, 1) + m(1, 3)) * invW; GLint ix1 = qRound((fx1 + 1) * m_device_rect.width() * qreal(0.5)); GLint iy1 = qRound((fy1 + 1) * m_device_rect.height() * qreal(0.5)); GLint ix2 = qRound((fx2 + 1) * m_device_rect.width() * qreal(0.5)); GLint iy2 = qRound((fy2 + 1) * m_device_rect.height() * qreal(0.5)); if (!scissorEnabled) { clipRect = QRect(ix1, iy1, ix2 - ix1, iy2 - iy1); glEnable(GL_SCISSOR_TEST); scissorEnabled = true; } else { clipRect &= QRect(ix1, iy1, ix2 - ix1, iy2 - iy1); } clipRect = clipRect.normalized(); glScissor(clipRect.x(), clipRect.y(), clipRect.width(), clipRect.height()); } else { if (!stencilEnabled) { if (!m_clip_program.isLinked()) { m_clip_program.addShaderFromSourceCode(QGLShader::Vertex, "attribute highp vec4 vCoord; \n" "uniform highp mat4 matrix; \n" "void main() { \n" " gl_Position = matrix * vCoord; \n" "}"); m_clip_program.addShaderFromSourceCode(QGLShader::Fragment, "void main() { \n" " gl_FragColor = vec4(0.81, 0.83, 0.12, 1.0); \n" // Trolltech green ftw! "}"); m_clip_program.bindAttributeLocation("vCoord", 0); m_clip_program.link(); m_clip_matrix_id = m_clip_program.uniformLocation("matrix"); } glStencilMask(0xff); // write mask glClearStencil(0); glClear(GL_STENCIL_BUFFER_BIT); glEnable(GL_STENCIL_TEST); glDisable(GL_DEPTH_TEST); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); m_clip_program.bind(); m_clip_program.enableAttributeArray(0); stencilEnabled = true; } glStencilFunc(GL_EQUAL, clipDepth, 0xff); // stencil test, ref, test mask glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // stencil fail, z fail, z pass const QSGGeometry *geometry = clip->geometry(); Q_ASSERT(geometry->attributeCount() > 0); const QSGGeometry::Attribute *a = geometry->attributes(); glVertexAttribPointer(0, a->tupleSize, a->type, GL_FALSE, geometry->stride(), geometry->vertexData()); m_clip_program.setUniformValue(m_clip_matrix_id, m); draw(clip); ++clipDepth; } clip = clip->clipList(); } if (stencilEnabled) { m_clip_program.disableAttributeArray(0); glEnable(GL_DEPTH_TEST); glStencilFunc(GL_EQUAL, clipDepth, 0xff); // stencil test, ref, test mask glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // stencil fail, z fail, z pass glStencilMask(0); // write mask bindable()->reactivate(); //glDepthMask(GL_TRUE); // must be reset correctly by caller. } else { glDisable(GL_STENCIL_TEST); } if (!scissorEnabled) glDisable(GL_SCISSOR_TEST); return stencilEnabled ? StencilClip : ScissorClip; }
void BezierDisplay::updateDisplay(QGraphicsItem * master, Bezier *bezier) { if (m_itemL0 == NULL) return; if (m_itemL1 == NULL) return; //if (m_itemE0 == NULL) return; //if (m_itemE1 == NULL) return; if (bezier == NULL || bezier->isEmpty()) { m_itemL0->setVisible(false); m_itemL1->setVisible(false); //m_itemE0->setVisible(false); //m_itemE1->setVisible(false); return; } //static double minD = 5; //static double radius = 6; //static double minDSqd = minD * minD; QRectF sr = master->scene()->sceneRect(); double x1, y1, x2, y2; QPointF p0 = master->mapToScene(bezier->endpoint0()); QPointF p1 = master->mapToScene(bezier->cp0()); GraphicsUtils::liangBarskyLineClip(p0.x(), p0.y(), p1.x(), p1.y(), sr.left(), sr.right(), sr.top(), sr.bottom(), x1, y1, x2, y2); m_itemL0->setLine(x1, y1, x2, y2); //if (GraphicsUtils::distanceSqd(bezier->endpoint0(), bezier->cp0()) > minDSqd) { //m_itemE0->setVisible(false); //} //else { //QRectF r(master->mapToScene(bezier->endpoint0()), QSizeF(0,0)); //r.adjust(-radius, -radius, radius, radius); //m_itemE0->setRect(r); //m_itemE0->setVisible(true); //} p0 = master->mapToScene(bezier->endpoint1()); p1 = master->mapToScene(bezier->cp1()); GraphicsUtils::liangBarskyLineClip(p0.x(), p0.y(), p1.x(), p1.y(), sr.left(), sr.right(), sr.top(), sr.bottom(), x1, y1, x2, y2); m_itemL1->setLine(x1, y1, x2, y2); //if (GraphicsUtils::distanceSqd(bezier->endpoint1(), bezier->cp1()) > minDSqd) { // m_itemE1->setVisible(false); //} //else { // QRectF r(master->mapToScene(bezier->endpoint1()), QSizeF(0,0)); // r.adjust(-radius, -radius, radius, radius); // m_itemE1->setRect(r); // m_itemE1->setVisible(true); //} m_itemL0->setVisible(true); m_itemL1->setVisible(true); }
void OrthogonalRenderer::drawTileLayer(QPainter *painter, const TileLayer *layer, const QRectF &exposed) const { QTransform savedTransform = painter->transform(); const int tileWidth = map()->tileWidth(); const int tileHeight = map()->tileHeight(); const QPointF layerPos(layer->x() * tileWidth, layer->y() * tileHeight); painter->translate(layerPos); int startX = 0; int startY = 0; int endX = layer->width(); int endY = layer->height(); if (!exposed.isNull()) { QMargins drawMargins = layer->drawMargins(); drawMargins.setTop(drawMargins.top() - tileHeight); drawMargins.setRight(drawMargins.right() - tileWidth); QRectF rect = exposed.adjusted(-drawMargins.right(), -drawMargins.bottom(), drawMargins.left(), drawMargins.top()); rect.translate(-layerPos); startX = qMax((int) rect.x() / tileWidth, 0); startY = qMax((int) rect.y() / tileHeight, 0); endX = qMin((int) std::ceil(rect.right()) / tileWidth + 1, endX); endY = qMin((int) std::ceil(rect.bottom()) / tileHeight + 1, endY); } QTransform baseTransform = painter->transform(); for (int y = startY; y < endY; ++y) { for (int x = startX; x < endX; ++x) { const Cell &cell = layer->cellAt(x, y); if (cell.isEmpty()) continue; const QPixmap &img = cell.tile->image(); const QPoint offset = cell.tile->tileset()->tileOffset(); qreal m11 = 1; // Horizontal scaling factor qreal m12 = 0; // Vertical shearing factor qreal m21 = 0; // Horizontal shearing factor qreal m22 = 1; // Vertical scaling factor qreal dx = offset.x() + x * tileWidth; qreal dy = offset.y() + (y + 1) * tileHeight - img.height(); if (cell.flippedAntiDiagonally) { // Use shearing to swap the X/Y axis m11 = 0; m12 = 1; m21 = 1; m22 = 0; // Compensate for the swap of image dimensions dy += img.height() - img.width(); } if (cell.flippedHorizontally) { m11 = -m11; m21 = -m21; dx += cell.flippedAntiDiagonally ? img.height() : img.width(); } if (cell.flippedVertically) { m12 = -m12; m22 = -m22; dy += cell.flippedAntiDiagonally ? img.width() : img.height(); } const QTransform transform(m11, m12, m21, m22, dx, dy); painter->setTransform(transform * baseTransform); painter->drawPixmap(0, 0, img); } } painter->setTransform(savedTransform); }
void QEglFSCursor::draw(const QRectF &r) { if (!m_program) { // one time initialization createShaderPrograms(); if (!m_cursorAtlas.texture) { createCursorTexture(&m_cursorAtlas.texture, m_cursorAtlas.image); m_cursorAtlas.image = QImage(); if (m_cursor.shape != Qt::BitmapCursor) m_cursor.texture = m_cursorAtlas.texture; } } if (m_cursor.shape == Qt::BitmapCursor && !m_cursor.customCursorImage.isNull()) { // upload the custom cursor createCursorTexture(&m_cursor.customCursorTexture, m_cursor.customCursorImage); m_cursor.texture = m_cursor.customCursorTexture; m_cursor.customCursorImage = QImage(); } Q_ASSERT(m_cursor.texture); glUseProgram(m_program); const GLfloat x1 = r.left(); const GLfloat x2 = r.right(); const GLfloat y1 = r.top(); const GLfloat y2 = r.bottom(); const GLfloat cursorCoordinates[] = { x1, y2, x2, y2, x1, y1, x2, y1 }; const GLfloat s1 = m_cursor.textureRect.left(); const GLfloat s2 = m_cursor.textureRect.right(); const GLfloat t1 = m_cursor.textureRect.top(); const GLfloat t2 = m_cursor.textureRect.bottom(); const GLfloat textureCoordinates[] = { s1, t2, s2, t2, s1, t1, s2, t1 }; glBindTexture(GL_TEXTURE_2D, m_cursor.texture); glEnableVertexAttribArray(m_vertexCoordEntry); glEnableVertexAttribArray(m_textureCoordEntry); glVertexAttribPointer(m_vertexCoordEntry, 2, GL_FLOAT, GL_FALSE, 0, cursorCoordinates); glVertexAttribPointer(m_textureCoordEntry, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates); glUniform1f(m_textureEntry, 0); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); // disable depth testing to make sure cursor is always on top glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisable(GL_BLEND); glBindTexture(GL_TEXTURE_2D, 0); glDisableVertexAttribArray(m_vertexCoordEntry); glDisableVertexAttribArray(m_textureCoordEntry); glUseProgram(0); }
bool OsmImport::parseDoc(QDomDocument &doc) { QDomNodeList list = doc.elementsByTagName("node"); for (int i = 0; i < list.count(); i++) { nodes.append(new osmNode(list.at(i).toElement())); } list = doc.elementsByTagName("way"); for (int i = 0; i < list.count(); i++) { ways.append(new osmWay(list.at(i).toElement(), nodes)); } bool doPrimary = ImportSettings::instance()->importPrimary(); bool doSecondary = ImportSettings::instance()->importSecondary(); bool doTertiary = ImportSettings::instance()->importTertiary(); bool doMotorway = ImportSettings::instance()->importMotorway(); bool doService = ImportSettings::instance()->importService(); bool doPath = ImportSettings::instance()->importPath(); bool doSteps = ImportSettings::instance()->importSteps(); bool doTrack = ImportSettings::instance()->importTrack(); bool doFootpath = ImportSettings::instance()->importFootway(); bool doResidential = ImportSettings::instance()->importResidential(); bool doLiving_street = ImportSettings::instance()->importLiving_street(); bool doCycleway = ImportSettings::instance()->importCycleway(); bool doTurning_circle = ImportSettings::instance()->importTurning_circle(); bool doPedestrian = ImportSettings::instance()->importPedestrian(); bool doUnclassified = ImportSettings::instance()->importUnclassified(); for (int i = 0; i < ways.count(); i++) { osmWay *w = ways.at(i); osmWay::wayType t = w->type; if ((t == osmWay::primary && doPrimary) || (t == osmWay::secondary && doSecondary) || (t == osmWay::tertiary && doTertiary) || (t == osmWay::motorway && doMotorway) || (t == osmWay::service && doService) || (t == osmWay::path && doPath) || (t == osmWay::steps && doSteps) || (t == osmWay::track && doTrack) || (t == osmWay::footway && doFootpath) || (t == osmWay::residential && doResidential) || (t == osmWay::living_street && doLiving_street) || (t == osmWay::cycleway && doCycleway) || (t == osmWay::turning_circle && doTurning_circle) || (t == osmWay::pedestrian && doPedestrian) || (t == osmWay::unclassified && doUnclassified)) { project->XVector = w->XVector; project->YVector = w->YVector; project->ZVector = w->ZVector; if (project->XVector.size() > 0) { project->addLineStrip(w->name,w->maxSpeed,w->bridge,w->numLanes,w->type); } } } qDeleteAll(ways.begin(), ways.end()); qDeleteAll(nodes.begin(), nodes.end()); ways.clear(); nodes.clear(); // resize BoundingBoxVisitor *visitor = new BoundingBoxVisitor(); project->getProjectData()->getRoadSystem()->accept(visitor); project->getProjectData()->getScenerySystem()->accept(visitor); QRectF box = visitor->getBoundingBox(); SetProjectDimensionsCommand *command = new SetProjectDimensionsCommand(project->getProjectData(), box.bottom() + 0.1 * box.height(), box.top() - 0.1 * box.height(), box.right() + 0.1 * box.width(), box.left() - 0.1 * box.width()); project->getProjectSettings()->executeCommand(command); return true; }
void SchemaView::configureObject(void) { Schema *schema=dynamic_cast<Schema *>(this->getSourceObject()); this->fetchChildren(); /* Only configures the schema view if the rectangle is visible and there are children objects. Otherwise the schema view is hidden */ if(schema->isRectVisible() && !children.isEmpty()) { QColor color; QRectF rect; QFont font; float sp_h=0, sp_v=0, txt_h=0; float x1=1000000, y1=1000000, x2=-1000000, y2=-1000000, width=0; QList<BaseObjectView *>::Iterator itr=children.begin(); //Configures the bounding rect based upon the children dimension while(itr!=children.end()) { rect.setTopLeft((*itr)->pos()); rect.setSize((*itr)->boundingRect().size()); if(rect.left() < x1) x1 = rect.left(); if(rect.right() > x2) x2 = rect.right(); if(rect.top() < y1) y1 = rect.top(); if(rect.bottom() > y2) y2 = rect.bottom(); itr++; } //Configures the schema name at the top sch_name->setText(/*Utf8String::create(*/schema->getName()); font=BaseObjectView::getFontStyle(ParsersAttributes::GLOBAL).font(); font.setItalic(true); font.setBold(true); font.setPointSizeF(font.pointSizeF() * 1.3f); sch_name->setFont(font); sch_name->setPos(HORIZ_SPACING, VERT_SPACING); txt_h=sch_name->boundingRect().height() + (2 * VERT_SPACING); //Configures the box with the points calculated above sp_h=(3 * HORIZ_SPACING); sp_v=(3 * VERT_SPACING) + txt_h; width=(x2-x1) + 1; if(width < sch_name->boundingRect().width()) width=sch_name->boundingRect().width(); rect.setTopLeft(QPointF(-sp_h, 0)); rect.setTopRight(QPointF(width + sp_h, 0)); rect.setBottomRight(QPointF(width + sp_h, y2-y1 + sp_v)); rect.setBottomLeft(QPointF(-sp_h, y2-y1 + sp_v)); box->setRect(rect); //Sets the schema view position this->setFlag(ItemSendsGeometryChanges, false); this->moveBy(-this->pos().x(),-this->pos().y()); this->setPos(QPointF(x1, y1 - txt_h)); schema->setPosition(this->mapToScene(rect.topLeft())); this->setFlag(ItemSendsGeometryChanges, true); color=schema->getFillColor(); color.setAlpha(80); box->setBrush(color); color=QColor(color.red()/3,color.green()/3,color.blue()/3, 80); box->setPen(QPen(color, 1, Qt::DashLine)); this->bounding_rect=rect; this->setVisible(true); this->setToolTip(/*Utf8String::create(*/schema->getName(true) + QString(" (") + schema->getTypeName() + QString(")")); sch_name->setToolTip(this->toolTip()); this->protected_icon->setPos(QPointF( sch_name->boundingRect().width() + sp_h, sch_name->pos().y() + VERT_SPACING )); this->configureObjectSelection(); this->configureProtectedIcon(); this->configurePositionInfo(this->pos()); this->configureSQLDisabledInfo(); } else this->setVisible(false); }
void KeyBoardPreview::paintEvent(QPaintEvent* event) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setBrush(QColor(0xd6, 0xd6, 0xd6)); p.drawRect(rect()); QPen pen; pen.setWidth(1); pen.setColor(QColor(0x58, 0x58, 0x58)); p.setPen(pen); p.setBrush(QColor(0x58, 0x58, 0x58)); p.setBackgroundMode(Qt::TransparentMode); p.translate(0.5, 0.5); int rx = 3; int x=6; int y=6; int first_key_w = 0; int remaining_x[] = {0,0,0,0}; int remaining_widths[] = {0,0,0,0}; for (int i = 0; i < 4; i++) { if (first_key_w > 0) { first_key_w = first_key_w*1.375; if (kb == &kbList[KB_105] && i == 3) first_key_w = key_w * 1.275; p.drawRoundedRect(QRectF(6, y, first_key_w, key_w), rx, rx); x = 6 + first_key_w + space; } else { first_key_w = key_w; } bool last_end = (i==1 && ! kb->kb_extended_return); int rw=usable_width-x; int ii=0; for (int k : kb->keys.at(i)) { QRectF rect = QRectF(x, y, key_w, key_w); if (ii == kb->keys.at(i).size()-1 && last_end) rect.setWidth(rw); p.drawRoundedRect(rect, rx, rx); rect.adjust(5, 1, 0, 0); p.setPen(QColor(0x9e, 0xde, 0x00)); p.setFont(upperFont); p.drawText(rect, Qt::AlignLeft | Qt::AlignTop, shift_text(k)); rect.setBottom(rect.bottom() - 2.5); p.setPen(QColor(0xff, 0xff, 0xff)); p.setFont(lowerFont); p.drawText(rect, Qt::AlignLeft | Qt::AlignBottom, regular_text(k)); rw = rw - space - key_w; x = x + space + key_w; ii = ii+1; p.setPen(pen); } remaining_x[i] = x; remaining_widths[i] = rw; if (i != 1 && i != 2) p.drawRoundedRect(QRectF(x, y, rw, key_w), rx, rx); y = y + space + key_w; } if (kb->kb_extended_return) { rx=rx*2; int x1 = remaining_x[1]; int y1 = 6 + key_w*1 + space*1; int w1 = remaining_widths[1]; int x2 = remaining_x[2]; int y2 = 6 + key_w*2 + space*2; // this is some serious crap... but it has to be so // maybe one day keyboards won't look like this... // one can only hope QPainterPath pp; pp.moveTo(x1, y1+rx); pp.arcTo(x1, y1, rx, rx, 180, -90); pp.lineTo(x1+w1-rx, y1); pp.arcTo(x1+w1-rx, y1, rx, rx, 90, -90); pp.lineTo(x1+w1, y2+key_w-rx); pp.arcTo(x1+w1-rx, y2+key_w-rx, rx, rx, 0, -90); pp.lineTo(x2+rx, y2+key_w); pp.arcTo(x2, y2+key_w-rx, rx, rx, -90, -90); pp.lineTo(x2, y1+key_w); pp.lineTo(x1+rx, y1+key_w); pp.arcTo(x1, y1+key_w-rx, rx, rx, -90, -90); pp.closeSubpath(); p.drawPath(pp); } else { x= remaining_x[2]; y = 6 + key_w*2 + space*2; p.drawRoundedRect(QRectF(x, y, remaining_widths[2], key_w), rx, rx); } QWidget::paintEvent(event); }
void MosaicAreaTool::userChangedBox() { bool latValid = false; bool lonValid = false; bool areaValid = false; if(!m_latLineEdit || !m_lonLineEdit || !m_areaLineEdit) { clearBox(); return; } QString latitude = m_latLineEdit->text(); if(latitude != "Null" && latitude != "") { int cursorPos = 0; QValidator::State validLat = m_latLineEdit->validator()->validate(latitude, cursorPos); if(validLat != QValidator::Acceptable) { QMessageBox::warning(getWidget(), "Error", "Latitude value must be in the range -90 to 90", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } else { latValid = true; } } //Validate longitude value QString longitude = m_lonLineEdit->text(); if(longitude != "Null" && longitude != "" && latValid) { int cursorPos = 0; QValidator::State validLon = m_lonLineEdit->validator()->validate(longitude, cursorPos); if(validLon != QValidator::Acceptable) { QMessageBox::warning(getWidget(), "Error", "Longitude value invalid", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } else { lonValid = true; } } QString areaString = m_areaLineEdit->text(); if(areaString != "Null" && areaString != "" && latValid && lonValid) { int cursorPos = 0; QValidator::State validArea = m_areaLineEdit->validator()->validate(areaString, cursorPos); if(validArea != QValidator::Acceptable) { QMessageBox::warning(getWidget(), "Error", "Area value invalid", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } else { areaValid = true; } } if(latValid && lonValid && areaValid) { double lat = IString(latitude.toStdString()).ToDouble(); double lon = IString(longitude.toStdString()).ToDouble(); double area = IString(areaString.toStdString()).ToDouble(); Projection *projection = getWidget()->getProjection(); Projection::ProjectionType ptype = projection->projectionType(); if (projection && ptype == Projection::Triaxial) { TProjection * tproj = (TProjection *) projection; if (tproj->SetGround(lat, lon)) { QPointF scenePos(projection->XCoord(), -1 * projection->YCoord()); QRectF sceneRect(getWidget()->getView()->sceneRect()); if(sceneRect.contains(scenePos)) { if(m_box != NULL) { clearBox(); } Distance distance(area, Distance::Meters); QPolygonF boxPoly; QRectF latLonRange = calcLatLonRange(QPointF(lon, lat), distance); double xStep = latLonRange.width() / 100.0; double yStep = latLonRange.height() / 100.0; bool hasPole = (latLonRange.top() == -90 || latLonRange.bottom() == 90); double yPos = latLonRange.top(); if (yPos != -90) { for(double xPos = latLonRange.left(); xPos <= latLonRange.right(); xPos += xStep) { if (tproj->SetGround(yPos, xPos)) { QPointF pos(tproj->XCoord(), -1 * tproj->YCoord()); boxPoly << pos; } } } double xPos = latLonRange.right(); for (double yPos = latLonRange.top(); !hasPole && yPos <= latLonRange.bottom(); yPos += yStep) { if (tproj->SetGround(yPos, xPos)) { QPointF pos(tproj->XCoord(), -1 * tproj->YCoord()); boxPoly << pos; } } yPos = latLonRange.bottom(); if (yPos != 90) { for (double xPos = latLonRange.right(); xPos >= latLonRange.left(); xPos -= xStep) { if (tproj->SetGround(yPos, xPos)) { QPointF pos(tproj->XCoord(), -1 * tproj->YCoord()); boxPoly << pos; } } } xPos = latLonRange.left(); for (double yPos = latLonRange.bottom(); !hasPole && yPos >= latLonRange.top(); yPos -= yStep) { if (tproj->SetGround(yPos, xPos)) { QPointF pos(tproj->XCoord(), -1 * tproj->YCoord()); boxPoly << pos; } } if (boxPoly.size() > 0) { boxPoly << boxPoly[0]; m_box = new QGraphicsPolygonItem(boxPoly); m_box->setZValue(DBL_MAX); getWidget()->getScene()->addItem(m_box); getWidget()->getView()->centerOn(scenePos); } } else { QString message = "Lat/Lon not within this view."; QMessageBox::information(getWidget(), "Cannot Calculate Box", message, QMessageBox::Ok); } } } } }
/** * Given a distance and a center lat,lon this will return the bounding lat,lon * rect. * * The distance is the distance across the entire rectangle (i.e. width and * height). */ QRectF MosaicAreaTool::calcLatLonRange(QPointF centerLatLon, Distance size) { Distance distanceFromCenter = size / 2.0; QRectF latLonBoundingBox; Angle centerLat(centerLatLon.y(), Angle::Degrees); Angle centerLon(centerLatLon.x(), Angle::Degrees); TProjection *tproj = (TProjection *) getWidget()->getProjection(); if (tproj) { bool longitudeWraps = false; Distance radius(tproj->LocalRadius(centerLat.degrees()), Distance::Meters); // First we can get the angle between the latitudes... // d = arcsin ( movementDistance / radiusDistance ) Angle deltaLat(asin( distanceFromCenter / radius ), Angle::Radians); latLonBoundingBox.setTop( (centerLat - deltaLat).degrees() ); if (latLonBoundingBox.top() < -90 && centerLatLon.y() != -90) { // Block infinite recursion if (centerLatLon.y() != 90) { qWarning("The pole is included in the area but not centered"); centerLatLon.setY(-90); return calcLatLonRange(centerLatLon, size); } else return QRectF(); } else if (centerLatLon.y() == -90) { longitudeWraps = true; } latLonBoundingBox.setBottom( (centerLat + deltaLat).degrees() ); if (latLonBoundingBox.bottom() > 90 && centerLatLon.y() != 90) { // Block infinite recursion if (centerLatLon.y() != -90) { qWarning("The pole is included in the area but not centered"); centerLatLon.setY(90); return calcLatLonRange(centerLatLon, size); } else return QRectF(); } else if (centerLatLon.y() == 90) { longitudeWraps = true; } // Now let's do lons... Angle widestLat( asin( sin(centerLat.radians()) / cos( distanceFromCenter / radius ) ), Angle::Radians); double valueToASin = sin(distanceFromCenter / radius) / cos(widestLat.radians()); if(valueToASin < -1 || valueToASin > 1) longitudeWraps = true; // Longitude wraps if (longitudeWraps) { if (tproj->Has360Domain()) { latLonBoundingBox.setLeft( 0 ); latLonBoundingBox.setRight( 360 ); } else { latLonBoundingBox.setLeft( -180 ); latLonBoundingBox.setRight( 180 ); } } else { Angle deltaLon( asin( sin(distanceFromCenter / radius) / cos(widestLat.radians())), Angle::Radians); latLonBoundingBox.setLeft( (centerLon - deltaLon).degrees() ); latLonBoundingBox.setRight( (centerLon + deltaLon).degrees() ); } } return latLonBoundingBox; }
void acCustomGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect) { // color Black QColor ColorBlack(0, 0, 0); // color White QColor ColorWhite(255, 255, 255); // Draw a line grid if (m_gridenabled != eCustomGraphicsScene_Grids::None) { painter->setPen(Qt::white); // Start point for Horizonal steps qreal startH = 0; //Start point for Virtical steps qreal startV = 0; switch (m_gridenabled) { case eCustomGraphicsScene_Grids::Block: { QImage image(":/CompressonatorGUI/Images/GridSolid.png"); QBrush brush(image); painter->fillRect(rect, brush); break; } case eCustomGraphicsScene_Grids::Lines: { // First fill the BackGround as black painter->fillRect(rect, ColorBlack); // draw horizontal grid lines painter->setPen(QPen(ColorWhite)); for (qreal y = startH; y < rect.bottom();) { y += m_gridStep; painter->drawLine(rect.left(), y, rect.right(), y); } // draw virtical grid lines for (qreal x = startV; x < rect.right();) { x += m_gridStep; painter->drawLine(x, rect.top(), x, rect.bottom()); } break; } case eCustomGraphicsScene_Grids::Dots: { // First fill the BackGround as black painter->fillRect(rect, ColorBlack); // draw points painter->setPen(QPen(ColorWhite)); for (qreal y = startH; y < rect.bottom();) { y += m_gridStep; // draw virtical grid lines for (qreal x = startV; x < rect.right();) { x += m_gridStep; painter->drawPoint(x, y); } } break; } default: { painter->fillRect(rect, ColorBlack); break; } } } else painter->fillRect(rect, ColorBlack); }
void RangeHistogram::paintEvent(QPaintEvent *e) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); const QBrush blackBrush(QColor(0, 0, 0)); const QBrush redBrush(QColor(60, 0, 0)); const QBrush greenBrush(QColor(0, 128, 0)); const QBrush whiteBrush(QColor(255, 255, 255)); QRectF r = rect(); p.eraseRect(r); r = r.marginsRemoved(QMarginsF(m_Margin, m_Margin, m_Margin, m_Margin)); p.fillRect(r, palette().brush(QPalette::Shadow)); QMarginsF border(m_Border, m_Border, m_Border, m_Border); border /= devicePixelRatioF(); r = r.marginsRemoved(border); p.fillRect(r, ValidRange() ? palette().brush(QPalette::Inactive, QPalette::Highlight) : redBrush); int whiteX = (int)(whiteDelta() * r.width()); int blackX = (int)(blackDelta() * r.width() + 0.5); QRectF blackPoint(r.topLeft(), QSize(blackX, r.height())); QRectF whitePoint(r.left() + whiteX, r.top(), r.width() - whiteX, r.height()); if(ValidRange()) { p.setPen(QPen(palette().color(QPalette::Dark))); p.drawLine(blackPoint.topRight(), blackPoint.bottomRight()); p.drawLine(whitePoint.topLeft(), whitePoint.bottomLeft()); } p.fillRect(whitePoint, whiteBrush); p.fillRect(blackPoint, blackBrush); if(!ValidRange()) return; if(!m_HistogramData.isEmpty()) { float minx = delta(m_HistogramMin); float maxx = delta(m_HistogramMax); uint32_t maxval = 0; for(int i = 0; i < m_HistogramData.count(); i++) { float x = (float)i / (float)m_HistogramData.count(); float xdelta = minx + x * (maxx - minx); if(xdelta >= 0.0f && xdelta <= 1.0f) { maxval = qMax(maxval, m_HistogramData[i]); } } if(maxval == 0) maxval = 1; for(int i = 0; i < m_HistogramData.count(); i++) { float x = (float)i / (float)m_HistogramData.count(); float y = (float)m_HistogramData[i] / (float)maxval; float xdelta = minx + x * (maxx - minx); if(xdelta >= 0.0f && xdelta <= 1.0f) { float segwidth = qMax(r.width() * (maxx - minx) / (float)m_HistogramData.count(), 1.0); QRectF barRect(QPointF(r.left() + r.width() * (minx + x * (maxx - minx)), r.bottom() - r.height() * y + 1), QSizeF(segwidth, r.height() * y)); p.fillRect(barRect, greenBrush); } } } QVector<QPointF> blackTriangle = {QPoint(blackPoint.right(), m_MarkerSize * 2), QPoint(blackPoint.right() + m_MarkerSize, 0), QPoint(blackPoint.right() - m_MarkerSize, 0)}; QPainterPath blackPath; blackPath.addPolygon(QPolygonF(blackTriangle)); p.fillPath(blackPath, palette().brush(QPalette::Dark)); QVector<QPointF> whiteTriangle = { QPoint(whitePoint.left(), whitePoint.bottom() - m_MarkerSize * 2 + m_Margin), QPoint(whitePoint.left() + m_MarkerSize, whitePoint.bottom() + m_Margin), QPoint(whitePoint.left() - m_MarkerSize, whitePoint.bottom() + m_Margin)}; QPainterPath whitePath; whitePath.addPolygon(QPolygonF(whiteTriangle)); p.fillPath(whitePath, palette().brush(QPalette::Dark)); blackTriangle[0] -= QPointF(0.0, 2.0) / devicePixelRatioF(); blackTriangle[1] += QPointF(-2.0, 1.0) / devicePixelRatioF(); blackTriangle[2] += QPointF(2.0, 1.0) / devicePixelRatioF(); blackPath = QPainterPath(); blackPath.addPolygon(QPolygonF(blackTriangle)); whiteTriangle[0] += QPointF(0.0, 2.0) / devicePixelRatioF(); whiteTriangle[1] -= QPointF(2.0, 1.0) / devicePixelRatioF(); whiteTriangle[2] += QPointF(2.0, -1.0) / devicePixelRatioF(); whitePath = QPainterPath(); whitePath.addPolygon(QPolygonF(whiteTriangle)); p.fillPath(blackPath, blackBrush); p.fillPath(whitePath, whiteBrush); }
void SingleCellViewGraphPanelPlotWidget::drawCoordinates(QPainter *pPainter, const QPointF &pCoordinates, const QColor &pBackgroundColor, const QColor &pForegroundColor, const Location &pLocation, const bool &pCanMoveLocation) { // Retrieve the size of coordinates as they will appear on the screen, // which means using the same font as the one used for the axes pPainter->setFont(axisFont(QwtPlot::xBottom)); QString coords = QString("(%1, %2)").arg(QString::number(pCoordinates.x()), QString::number(pCoordinates.y())); QRect desktopGeometry = qApp->desktop()->availableGeometry(); QRectF coordsRect = pPainter->boundingRect(QRectF(0.0, 0.0, desktopGeometry.width(), desktopGeometry.height()), coords); // Determine where the coordinates and its background should be drawn QPoint coordinates = QPoint(canvasMap(QwtPlot::xBottom).transform(pCoordinates.x()), canvasMap(QwtPlot::yLeft).transform(pCoordinates.y())); switch (pLocation) { case TopLeft: coordsRect.moveTo(coordinates.x()-coordsRect.right()-1, coordinates.y()-coordsRect.bottom()-1); break; case TopRight: coordsRect.moveTo(coordinates.x()+2, coordinates.y()-coordsRect.bottom()-1); break; case BottomLeft: coordsRect.moveTo(coordinates.x()-coordsRect.right()-1, coordinates.y()+2); break; case BottomRight: coordsRect.moveTo(coordinates.x()+2, coordinates.y()+2); break; } if (pCanMoveLocation) { if (coordsRect.top() < 0) coordsRect.moveTop(coordinates.y()+2); if (coordsRect.left() < 0) coordsRect.moveLeft(coordinates.x()+2); if (coordsRect.bottom() > plotLayout()->canvasRect().height()) coordsRect.moveTop(coordinates.y()-coordsRect.height()-1); if (coordsRect.right() > plotLayout()->canvasRect().width()) coordsRect.moveLeft(coordinates.x()-coordsRect.width()-1); } // Draw a filled rectangle to act as the background of the coordinates // we are to show pPainter->fillRect(coordsRect, pBackgroundColor); // Draw the text for the coordinates, using a white pen QPen pen = pPainter->pen(); pen.setColor(pForegroundColor); pPainter->setPen(pen); pPainter->drawText(coordsRect, coords); }