void QRectFPropertyItem::setChildValues()
{
   if (!m_isSettingChildren)
   {
      m_isSettingChildren = true;

      QRectF v = qvariant_cast<QRectF>(m_metaProperty.read(m_parent->qObject()));

      for (int i = 0; i < m_children.count(); i++)
      {
         QPropertyItem* child = m_children[i];
         QString propertyName = child->name();
         QVariant tval;

         if (propertyName == "X")
         {
            tval = v.x();
         }
         else if (propertyName == "Y")
         {
            tval = v.y();
         }
         else if (propertyName == "Width")
         {
            tval = v.width();
         }
         else if (propertyName == "Height")
         {
            tval = v.height();
         }
         m_model->setData(child->index(), tval);
      }


      m_isSettingChildren = false;
   }
}
Esempio n. 2
0
void CpuPieMarker::draw(QPainter *p,
    const QwtScaleMap &, const QwtScaleMap &,
    const QRectF &rect) const
{
    const CpuPlot *cpuPlot = (CpuPlot *)plot();

    const QwtScaleMap yMap = cpuPlot->canvasMap(QwtPlot::yLeft);

    const int margin = 5;

    QRect pieRect;
    pieRect.setX(rect.x() + margin);
    pieRect.setY(rect.y() + margin);
    pieRect.setHeight( qRound(yMap.transform(80.0)) );
    pieRect.setWidth( pieRect.height() );

    const int dataType[] = { CpuPlot::User, CpuPlot::System, CpuPlot::Idle };

    int angle = (int)(5760 * 0.75);
    for ( unsigned int i = 0;
        i < sizeof(dataType) / sizeof(dataType[0]); i++ )
    {
        const QwtPlotCurve *curve = cpuPlot->cpuCurve(dataType[i]);
        if ( curve->dataSize() > 0 )
        {
            const int value = (int)(5760 * curve->sample(0).y() / 100.0);

            p->save();
            p->setBrush(QBrush(curve->pen().color(), Qt::SolidPattern));
            if ( value != 0 )
                p->drawPie(pieRect, -angle, -value);
            p->restore();

            angle += value;
        }
    }
}
void ChartItem::paint(QPainter *painter)
{
    if (m_bars.count() == 0)
        return;

    qreal minimum = m_bars[0]->value();
    qreal maximum = minimum;

    for (int i = 1; i < m_bars.count(); ++i) {
        minimum = qMin(minimum, m_bars[i]->value());
        maximum = qMax(maximum, m_bars[i]->value());
    }

    if (maximum == minimum)
        return;

    painter->save();

    const QRectF rect = boundingRect();
    
    qreal scale = rect.height()/(maximum - minimum);
    qreal barWidth = rect.width()/m_bars.count();

    for (int i = 0; i < m_bars.count(); ++i) {
        BarItem *bar = m_bars[i];
        qreal barEdge1 = scale * (maximum - bar->value());
        qreal barEdge2 = scale * maximum;
        QRectF barRect(rect.x() + i * barWidth,
                       rect.y() + qMin(barEdge1, barEdge2),
                       barWidth, qAbs(barEdge1 - barEdge2));

        painter->setBrush(bar->color());
        painter->drawRect(barRect);
    }

    painter->restore();
}
/*!
  \brief Draw the spectrogram

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rectangle of the canvas in painter coordinates

  \sa setDisplayMode(), renderImage(),
      QwtPlotRasterItem::draw(), drawContourLines()
*/
void QwtPlotSpectrogram::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( d_data->displayMode & ImageMode )
        QwtPlotRasterItem::draw( painter, xMap, yMap, canvasRect );

    if ( d_data->displayMode & ContourMode )
    {
        // Add some pixels at the borders
        const int margin = 2;
        QRectF rasterRect( canvasRect.x() - margin, canvasRect.y() - margin,
            canvasRect.width() + 2 * margin, canvasRect.height() + 2 * margin );

        QRectF area = QwtScaleMap::invTransform( xMap, yMap, rasterRect );

        const QRectF br = boundingRect();
        if ( br.isValid() )
        {
            area &= br;
            if ( area.isEmpty() )
                return;

            rasterRect = QwtScaleMap::transform( xMap, yMap, area );
        }

        QSize raster = contourRasterSize( area, rasterRect.toRect() );
        raster = raster.boundedTo( rasterRect.toRect().size() );
        if ( raster.isValid() )
        {
            const QwtRasterData::ContourLines lines =
                renderContourLines( area, raster );

            drawContourLines( painter, xMap, yMap, lines );
        }
    }
}
void QEmulationPaintEngine::fill(const QVectorPath &path, const QBrush &brush)
{
    QPainterState *s = state();

    if (s->bgMode == Qt::OpaqueMode) {
        Qt::BrushStyle style = brush.style();
        if ((style >= Qt::Dense1Pattern && style <= Qt::DiagCrossPattern) || (style == Qt::TexturePattern ))
            real_engine->fill(path, s->bgBrush);
    }

    Qt::BrushStyle style = qbrush_style(brush);
    if (style >= Qt::LinearGradientPattern && style <= Qt::ConicalGradientPattern) {
        const QGradient *g = brush.gradient();

        if (g->coordinateMode() > QGradient::LogicalMode) {
            if (g->coordinateMode() == QGradient::StretchToDeviceMode) {
                QBrush copy = brush;
                QTransform mat = copy.transform();
                mat.scale(real_engine->painter()->device()->width(), real_engine->painter()->device()->height());
                copy.setTransform(mat);
                real_engine->fill(path, copy);
                return;
            } else if (g->coordinateMode() == QGradient::ObjectBoundingMode) {
                QBrush copy = brush;
                QTransform mat = copy.transform();
                QRectF r = path.controlPointRect();
                mat.translate(r.x(), r.y());
                mat.scale(r.width(), r.height());
                copy.setTransform(mat);
                real_engine->fill(path, copy);
                return;
            }
        }
    }

    real_engine->fill(path, brush);
}
Esempio n. 6
0
	QRectF
	FlowDesigner::calculatePortBoundingBox(const Port &p, const QRectF &compBounds) {
		const Component *comp = p.getComponent();
		const std::vector<Port *> &ports = comp->getPorts();

		int pos = 0;

		for (Port *port : ports) {
			if (port->getLocation() == p.getLocation()) {
				if (port != &p) {
					pos++;
				} else break;
			}
		}

	    float xPos = compBounds.x();
		float yPos = compBounds.y() +
			COMPONENT_CORNER_RADIUS + m_fontMetrics.height() * (1.5f + pos);

		switch(p.getLocation()) {
		case PortLocation::TOP: {
			return QRectF(0, 0, 0, 0);
		} break;
		case PortLocation::BOTTOM: {
			return QRectF(0, 0, 0, 0);
		} break;
		case PortLocation::LEFT: {
			xPos += LINK_CIRCLE_OFFSET;
		} break;
		case PortLocation::RIGHT: {
			xPos += compBounds.width() - LINK_CIRCLE_OFFSET - 2 * LINK_CIRCLE_RADIUS;
		} break;
		default: break;
		}

		return QRectF(xPos, yPos, 2 * LINK_CIRCLE_RADIUS, 2 * LINK_CIRCLE_RADIUS);
	}
Esempio n. 7
0
QList<MapWidget::Position> MapWidget::getEllipsePositions(int markersHeight, const QRectF &ellipseRect) const
{
    qreal hRadius = ellipseRect.width()/2.0;
    qreal vRadius = ellipseRect.height()/2.0;
    qreal elipseHCenter = ellipseRect.x() + hRadius;
    qreal elipseVCenter = ellipseRect.y() + vRadius;

    QList<MapWidget::Position> positions;

    qreal angle = -M_PI/2.0; //start angle
    int index = 0;
    Q_ASSERT(markersHeight > 0);
    const int maxPositions = height()/markersHeight * 2.0;
    static const qreal MAX_ANGLE = M_PI * 1.5;
    static const qreal STEP = 0.1;
    while (index < maxPositions && angle < MAX_ANGLE) {
        qreal x = elipseHCenter + (std::cos(angle) * hRadius);
        qreal y = elipseVCenter + (std::sin(angle) * vRadius);
        positions.append(MapWidget::Position(QPointF(x, y), index++));
        qreal tempY;
        do{
            angle += STEP;
            tempY = elipseVCenter + (std::sin(angle) * vRadius);
        }
        while (qAbs(tempY - y) <= markersHeight && angle < MAX_ANGLE);
    }

    // the last position is too close to the first position?
    if (positions.size() >= 2) {
        const MapWidget::Position &first = positions.first();
        const MapWidget::Position &last = positions.last();
        if (qAbs(last.coords.y() - first.coords.y()) < markersHeight)
            positions.removeLast(); // discard the last
    }

    return positions;
}
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 );
        }
    }
}
Esempio n. 9
0
int AbstractClipItem::mouseOverKeyFrames(QPointF pos, double maxOffset)
{
    const QRectF br = sceneBoundingRect();
    double maxw = br.width() / cropDuration().frames(m_fps);
    double maxh = br.height() / 100.0 * m_keyframeFactor;
    if (m_keyframes.count() > 0) {
        QMap<int, int>::const_iterator i = m_keyframes.constBegin();
        double x1;
        double y1;
        while (i != m_keyframes.constEnd()) {
            x1 = br.x() + maxw * (i.key() - cropStart().frames(m_fps));
            y1 = br.bottom() - (i.value() - m_keyframeOffset) * maxh;
            if (qAbs(pos.x() - x1) < maxOffset && qAbs(pos.y() - y1) < 10) {
                setToolTip('[' + QString::number((GenTime(i.key(), m_fps) - cropStart()).seconds(), 'f', 2) + i18n("seconds") + ", " + QString::number(i.value(), 'f', 1) + ']');
                return i.key();
            } else if (x1 > pos.x()) {
                break;
            }
            ++i;
        }
    }
    setToolTip(QString());
    return -1;
}
Esempio n. 10
0
/*!
  Render a legend entry into a given rectangle.

  \param painter Painter
  \param widget Widget representing a legend entry
  \param rect Bounding rectangle
  \param fillBackground When true, fill rect with the widget background 

  \note When widget is not derived from QwtLegendLabel renderItem
        does nothing beside the background
*/
void QwtLegend::renderItem( QPainter *painter, 
    const QWidget *widget, const QRectF &rect, bool fillBackground ) const
{
    if ( fillBackground )
    {
        if ( widget->autoFillBackground() ||
            widget->testAttribute( Qt::WA_StyledBackground ) )
        {
            QwtPainter::drawBackgound( painter, rect, widget );
        }
    }

    const QwtLegendLabel *label = qobject_cast<const QwtLegendLabel *>( widget );
    if ( label )
    {
        // icon

        const QwtGraphic &icon = label->data().icon();
        const QSizeF sz = icon.defaultSize();

        const QRectF iconRect( rect.x() + label->margin(),
            rect.center().y() - 0.5 * sz.height(), 
            sz.width(), sz.height() );

        icon.render( painter, iconRect, Qt::KeepAspectRatio );

        // title

        QRectF titleRect = rect;
        titleRect.setX( iconRect.right() + 2 * label->spacing() );

        painter->setFont( label->font() );
        painter->setPen( label->palette().color( QPalette::Text ) );
        const_cast< QwtLegendLabel *>( label )->drawText( painter, titleRect );
    }
}
void GenericSurfacePainter::paint(quint8 *data,
        const BufferFormat & frameFormat,
        QPainter *painter,
        const PaintAreas & areas)
{
    Q_ASSERT(m_imageFormat != QImage::Format_Invalid);

    QImage image(
        data,
        frameFormat.frameSize().width(),
        frameFormat.frameSize().height(),
        frameFormat.bytesPerLine(),
        m_imageFormat);

    QRectF sourceRect = areas.sourceRect;
    sourceRect.setX(sourceRect.x() * frameFormat.frameSize().width());
    sourceRect.setY(sourceRect.y() * frameFormat.frameSize().height());
    sourceRect.setWidth(sourceRect.width() * frameFormat.frameSize().width());
    sourceRect.setHeight(sourceRect.height() * frameFormat.frameSize().height());

    painter->fillRect(areas.blackArea1, Qt::black);
    painter->drawImage(areas.videoArea, image, sourceRect);
    painter->fillRect(areas.blackArea2, Qt::black);
}
void GraphicsContext::beginTransparencyLayer(float opacity)
{
    if (paintingDisabled())
        return;

    int x, y, w, h;
    x = y = 0;
    QPainter *p = m_data->p();
    const QPaintDevice *device = p->device();
    w = device->width();
    h = device->height();

    QRectF clip = p->clipPath().boundingRect();
    QRectF deviceClip = p->transform().mapRect(clip);
    x = int(qBound(qreal(0), deviceClip.x(), (qreal)w));
    y = int(qBound(qreal(0), deviceClip.y(), (qreal)h));
    w = int(qBound(qreal(0), deviceClip.width(), (qreal)w) + 2);
    h = int(qBound(qreal(0), deviceClip.height(), (qreal)h) + 2);

    TransparencyLayer * layer = new TransparencyLayer(m_data->p(), QRect(x, y, w, h));

    layer->opacity = opacity;
    m_data->layers.push(layer);
}
Esempio n. 13
0
void ossimGui::ImageScrollWidget::paintWidget(QPainter& painter)
{
   if((m_layers->numberOfLayers() > 1)&&(m_multiLayerAlgorithm!=NO_ALGORITHM))
   {
      paintMultiLayer(painter);
   }
   else 
   {
      ossimRefPtr<Layer> topLayer    = m_layers->layer((ossim_uint32)0);
      if(topLayer.valid())
      {
         ossimRefPtr<StaticTileImageCache> topTileCache = topLayer->tileCache();
         if(topTileCache.valid())
         {
            ossimIrect rect          = topTileCache->getRect();
            QRectF rectF = m_scrollToLocal.mapRect(QRectF(rect.ul().x, rect.ul().y, rect.width(), rect.height()));
            
            ossimIpt topOriginOffset = ossimDpt(rectF.x(), rectF.y());
            painter.drawImage(topOriginOffset.x, topOriginOffset.y, topTileCache->getCache());
         }
      }
   }
   if(!m_trackPoint.hasNans()&&m_trackingFlag&&!m_mouseInsideFlag)
   {
      drawCursor(painter);
   }


   // Temporary marker control
   // if (m_drawPts == true)
   // {
   //    m_regOverlay->drawMeas(painter, m_viewToLocal);
   // }
   // m_regOverlay->drawProj(painter, m_viewToLocal);

}
Esempio n. 14
0
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);
    }
}
Esempio n. 15
0
GuideLabelNode::GuideLabelNode(QString name, LabelsItem::label_t type)
    :m_textTexture(new QSGSimpleTextureNode), m_name(name)
{
    appendChildNode(&debugRect);
    debugRect.setColor(QColor("green"));
    QColor color;
    switch(type) {
        case LabelsItem::label_t::CONSTEL_NAME_LABEL:
            color = KStarsData::Instance()->colorScheme()->colorNamed( "CNameColor" );
            break;
        case LabelsItem::label_t::HORIZON_LABEL:
            color = KStarsData::Instance()->colorScheme()->colorNamed( "CompassColor" );
            break;
        default:
            color = KStarsData::Instance()->colorScheme()->colorNamed( "UserLabelColor" );
    }

    m_textTexture->setTexture(SkyMapLite::Instance()->textToTexture(name, color));
    m_opacity->appendChildNode(m_textTexture);

    m_textSize = m_textTexture->texture()->textureSize();
    QRectF oldRect = m_textTexture->rect();
    m_textTexture->setRect(QRect(oldRect.x(),oldRect.y(),m_textSize.width(),m_textSize.height()));
}
Esempio n. 16
0
/*protected*/ void DrawCircle::makeFigure() {
    ControlPanelEditor* ed = _parent->getEditor();
    QRectF r = ed->getSelectRect();
    if (!r.isValid()) {
        return;
    }
    _radius = qMax(r.width(), r.height());
    QGraphicsEllipseItem* rr = new QGraphicsEllipseItem(0, 0, _radius, _radius);
    rr->setBrush(QBrush(_fillColor));
    rr->setPen(QPen(QBrush(_lineColor),_lineWidth));
    PositionableCircle* ps = new PositionableCircle(ed, rr);
    ps->_itemGroup = new MyGraphicsItemGroup();
    ps->_itemGroup->setName("PositionableCircle");

    ps->_itemGroup->addToGroup(rr);
    ps->setLocation(r.x(), r.y());
//    ps->setHeight(_height);
//    ps->setWidth(_width);
    ps->setDisplayLevel(ControlPanelEditor::MARKERS);
    setDisplayParams(ps);
    ps->updateSize();
    ed->putItem(ps);
    DrawFrame::closingEvent(true);
}
Esempio n. 17
0
void EmulatedCardWindow::drawRoundedCorners(QPainter* painter) {

	QPainter::CompositionMode compositionMode = painter->compositionMode();


	QRectF emuRect;
    OrientationEvent::Orientation orient = WindowServer::instance()->getUiOrientation();

	//No rounded corners in full screen mode.
	if (m_fullScreenMode) return;

	emuRect = rotateEmulationBoundingRect(0);

	painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
	painter->drawPixmap(emuRect.x(), emuRect.y(),
						*m_upperLeftCorner);

	painter->drawPixmap(emuRect.topRight().x() - m_upperRightCorner->width(),
						emuRect.topRight().y(),
						*m_upperRightCorner);

	painter->drawPixmap(emuRect.bottomLeft().x(),
						emuRect.bottomLeft().y() - m_lowerLeftCorner->height(),
						*m_lowerLeftCorner);

	painter->drawPixmap(emuRect.bottomRight().x() - m_lowerRightCorner->width(),
						emuRect.bottomRight().y() - m_lowerRightCorner->height(),
						*m_lowerRightCorner);

	//It's handy debugging to uncomment these lines
	//painter->setPen(0xffffff);
	//painter->drawRect(emuRect);

	painter->setCompositionMode(compositionMode);

}
Game_Object::Game_Object(QImage *Image, int Image_Number, QRectF RectTarget, qreal Rotate)
{
    this->Image = Image;
    this->Image_Number = Image_Number;
    this->Image_Id = 0;
    this->RectTarget = RectTarget;
    this->X = RectTarget.x();
    this->Y = RectTarget.y();
    this->Width = RectTarget.width();
    this->Height = RectTarget.height();

    this->Frame_Width = this->Image->width() / this->Image_Number;

    this->RectSource = QRectF(this->Frame_Width * this->Image_Id,
                              0,
                              this->Frame_Width * (this->Image_Id+1),
                              this->Image->height());

    this->Rotate = Rotate;

    QMatrix matrix_rotate;
    Rotate_Image = this->Image->copy(RectSource.x(), RectSource.y(), RectSource.width(), RectSource.height());
    Rotate_Image = Rotate_Image.transformed(matrix_rotate.rotate(Rotate), Qt::FastTransformation);
}
Esempio n. 19
0
void BaseViewer::viewportInfo()
{
#ifdef SHOW_VIEWPORT_INFO
    // display visible scene zone
    QRect wr = _ui->_view->viewport()->rect();
    SD_TRACE(QString("view rect : (%1, %2) | %3, %4")
             .arg(wr.x())
             .arg(wr.y())
             .arg(wr.width())
             .arg(wr.height()));

    QRectF r = _ui->_view->mapToScene(wr).boundingRect();
    SD_TRACE(QString("visible scene rect : (%1, %2) | %3, %4")
             .arg(r.x())
             .arg(r.y())
             .arg(r.width())
             .arg(r.height()));

    double sx = _ui->_view->matrix().m11();
    double sy = _ui->_view->matrix().m22();
    SD_TRACE(QString("view scale : %1, %2").arg(sx).arg(sy));
#endif

}
Esempio n. 20
0
/*!
    From QGraphicsLayout.
 */
void HbListLayout::setGeometry( const QRectF &rect )
{
    QGraphicsLayout::setGeometry(rect);
    QRectF effectiveRect = geometry();

    // TODO: Apply margins?
    //qreal left, top, right, bottom;
    //getContentsMargins(&left, &top, &right, &bottom);
    //effectiveRect.adjust(+left, +top, -right, -bottom);

    qreal y = effectiveRect.y();
    int itemCount = count();
    for ( int i = 0; i < itemCount; i++ ) {
        QGraphicsLayoutItem *item = itemAt( i );
        qreal itemHeight = item->preferredHeight();
        if (item->graphicsItem()->transform().isScaling()) {
            itemHeight *= item->graphicsItem()->transform().m22();
        }

        QRectF itemRect(effectiveRect.x(), y, effectiveRect.width(), itemHeight);
        item->setGeometry(itemRect);
        y += itemHeight;
    }
}
Esempio n. 21
0
void
BackdropGui::createGui()
{
    NodeGui::createGui();

    _imp->label = new NodeGraphTextItem(getDagGui(), this, false);
    _imp->label->setDefaultTextColor( QColor(0, 0, 0, 255) );
    _imp->label->setZValue(getBaseDepth() + 1);

    EffectInstancePtr effect = getNode()->getEffectInstance();
    assert(effect);
    Backdrop* isBd = dynamic_cast<Backdrop*>( effect.get() );
    assert(isBd);

    QObject::connect( isBd, SIGNAL(labelChanged(QString)), this, SLOT(onLabelChanged(QString)) );

    refreshTextLabelFromKnob();

    // Make the backdrop large enough to contain the selected nodes and position it correctly
    const NodesGuiList& selectedNodes =  getDagGui()->getSelectedNodes();
    QRectF bbox;
    for (NodesGuiList::const_iterator it = selectedNodes.begin(); it != selectedNodes.end(); ++it) {
        QRectF nodeBbox = (*it)->mapToScene( (*it)->boundingRect() ).boundingRect();
        bbox = bbox.united(nodeBbox);
    }

    double border50 = mapToScene( QPoint(50, 0) ).x();
    double border0 = mapToScene( QPoint(0, 0) ).x();
    double border = border50 - border0;
    double headerHeight = getFrameNameHeight();
    QPointF scenePos(bbox.x() - border, bbox.y() - border);

    setPos( mapToParent( mapFromScene(scenePos) ) );
    resize(bbox.width() + 2 * border, bbox.height() + 2 * border - headerHeight);

}
Esempio n. 22
0
 void advance(qreal t, const QRectF &rect) {
    pos += vel * t;
    bounce(pos.rx(), vel.rx(), rect.x(), rect.x() + rect.width());
    bounce(pos.ry(), vel.ry(), rect.y(), rect.y() + rect.height());
 }
Esempio n. 23
0
void QgsGCPCanvasItem::paint( QPainter* p )
{
  QgsRenderContext context;
  if ( !setRenderContextVariables( p, context ) )
  {
    return;
  }

  p->setRenderHint( QPainter::Antialiasing );

  bool enabled = true;
  QgsPoint worldCoords;
  int id = -1;

  if ( mDataPoint )
  {
    enabled = mDataPoint->isEnabled();
    worldCoords = mDataPoint->mapCoords();
    id = mDataPoint->id();
  }

  p->setOpacity( enabled ? 1.0 : 0.3 );

  // draw the point
  p->setPen( Qt::black );
  p->setBrush( mPointBrush );
  p->drawEllipse( -2, -2, 5, 5 );

  QSettings s;
  bool showIDs = s.value( "/Plugin-GeoReferencer/Config/ShowId" ).toBool();
  bool showCoords = s.value( "/Plugin-GeoReferencer/Config/ShowCoords" ).toBool();

  QString msg;
  if ( showIDs && showCoords )
  {
    msg = QString( "%1\nX %2\nY %3" ).arg( QString::number( id ) ).arg( QString::number( worldCoords.x(), 'f' ) ).arg( QString::number( worldCoords.y(), 'f' ) );
  }
  else if ( showIDs )
  {
    msg = msg = QString::number( id );
  }
  else if ( showCoords )
  {
    msg = QString( "X %1\nY %2" ).arg( QString::number( worldCoords.x(), 'f' ) ).arg( QString::number( worldCoords.y(), 'f' ) );
  }

  if ( !msg.isEmpty() )
  {
    p->setBrush( mLabelBrush );
    QFont textFont( "helvetica" );
    textFont.setPixelSize( fontSizePainterUnits( 12, context ) );
    p->setFont( textFont );
    QRectF textBounds = p->boundingRect( 3 * context.scaleFactor(), 3 * context.scaleFactor(), 5 * context.scaleFactor(), 5 * context.scaleFactor(), Qt::AlignLeft, msg );
    mTextBoxRect = QRectF( textBounds.x() - context.scaleFactor() * 1, textBounds.y() - context.scaleFactor() * 1, \
                           textBounds.width() + 2 * context.scaleFactor(), textBounds.height() + 2 * context.scaleFactor() );
    p->drawRect( mTextBoxRect );
    p->drawText( textBounds, Qt::AlignLeft, msg );
  }

  if ( data( 0 ) != "composer" ) //draw residuals only on screen
  {
    drawResidualArrow( p, context );
  }
}
Esempio n. 24
0
QSGNode* OMX_MediaProcessorElement::updatePaintNode(QSGNode*, UpdatePaintNodeData*)
{
    if (!m_texProvider) {
        m_texProvider = new OMX_TextureProviderQQuickItem(this);
        m_mediaProc   = new OMX_MediaProcessor(m_texProvider);
        connect(m_mediaProc, SIGNAL(playbackCompleted()), this, SIGNAL(playbackCompleted()));
        connect(m_mediaProc, SIGNAL(playbackStarted()), this, SIGNAL(playbackStarted()));

        // Open if filepath is set.
        // TODO: Handle errors.
        if (!m_source.isNull()) {
            //if (QFile(m_source).exists()) {
                if (openMedia(m_source))
                    m_mediaProc->play();
            //}
            //else {
                LOG_WARNING(LOG_TAG, "File does not exist.");
            //}
        }
    }

    return NULL;

#if 0
    QSGGeometryNode* node = 0;
    QSGGeometry* geometry = 0;

    if (!oldNode) {
        // Create the node.
        node = new QSGGeometryNode;
        geometry = new QSGGeometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4);
        geometry->setDrawingMode(GL_TRIANGLE_STRIP);
        node->setGeometry(geometry);
        node->setFlag(QSGNode::OwnsGeometry);

        // TODO: Who is freeing this?
        // TODO: I cannot know the texture size here.
        QSGOpaqueTextureMaterial* material = new QSGOpaqueTextureMaterial;
        m_sgtexture = new OMX_SGTexture(m_texture, QSize(1920, 1080));
        material->setTexture(m_sgtexture);
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);

#ifdef ENABLE_VIDEO_PROCESSOR
        QPlatformNativeInterface* nativeInterface =
                QGuiApplicationPrivate::platformIntegration()->nativeInterface();
        Q_ASSERT(nativeInterface);
        EGLDisplay eglDisplay = nativeInterface->nativeResourceForIntegration("egldisplay");
        EGLContext eglContext = nativeInterface->nativeResourceForContext(
                    "eglcontext",
                    QOpenGLContext::currentContext()
                    );
#endif

        // Provider MUST be built in this thread.
        m_provider  = new OMX_TextureProviderQQuickItem(this);
#ifdef ENABLE_VIDEO_PROCESSOR
        m_videoProc = new OMX_VideoProcessor(eglDisplay, eglContext, m_provider);
        connect(m_videoProc, SIGNAL(textureReady(uint)), this, SLOT(onTextureChanged(uint)));
        if (!m_source.isNull())
            m_videoProc->setVideoPath(m_source);
        if (m_playScheduled) {
            m_timer->start(30);
            m_videoProc->play();
        }
#elif ENABLE_MEDIA_PROCESSOR
        LOG_VERBOSE(LOG_TAG, "Starting video using media processor...");
        m_mediaProc = new OMX_MediaProcessor(m_provider);
        m_mediaProc->setFilename("/home/pi/usb/Cars2.mkv", m_texture);
        //if (m_playScheduled) {
            m_timer->start(40);
            m_mediaProc->play();
        //}
#else
        LOG_VERBOSE(LOG_TAG, "Starting video...");
        QtConcurrent::run(&startVideo, m_provider, this);
        m_timer->start(30);
#endif
    }
    else {
        node = static_cast<QSGGeometryNode*>(oldNode);
        geometry = node->geometry();
        geometry->allocate(4);

        // Update texture in the node if needed.
        QSGOpaqueTextureMaterial* material = (QSGOpaqueTextureMaterial*)node->material();
        if (m_texture != (GLuint)material->texture()->textureId()) {
            // TODO: Does setTextureId frees the prev texture?
            // TODO: I should the given the texture size.
            LOG_ERROR(LOG_TAG, "Updating texture to %u!", m_texture);
            material = new QSGOpaqueTextureMaterial;
            m_sgtexture->setTexture(m_texture, QSize(1920, 1080));
        }
    }

    // Create the vertices and map to texture.
    QRectF bounds = boundingRect();
    QSGGeometry::TexturedPoint2D* vertices = geometry->vertexDataAsTexturedPoint2D();
    vertices[0].set(bounds.x(), bounds.y() + bounds.height(), 0.0f, 0.0f);
    vertices[1].set(bounds.x() + bounds.width(), bounds.y() + bounds.height(), 1.0f, 0.0f);
    vertices[2].set(bounds.x(), bounds.y(), 0.0f, 1.0f);
    vertices[3].set(bounds.x() + bounds.width(), bounds.y(), 1.0f, 1.0f);
    return node;
#endif
}
Esempio n. 25
0
MovableRectItem::MovableRectItem(const QRectF &rect, const QRectF &size,
                                 SelectionArrowItem *topCircle, SelectionArrowItem *bottomCircle)
    : QGraphicsRectItem(rect), _currentRect(size), _initPos(rect.x(), rect.y()),
      _topCircle(topCircle), _bottomCircle(bottomCircle) {
  setFlags(QGraphicsItem::ItemIsMovable);
}
Esempio n. 26
0
QList<int> Database::advanceSearch(const QString &keyword, const QDate &startDate, const QDate &endDate, const QTime &startTime, const QTime &endTime, int group, int domain, const QRectF & geo, const QString & weather )
{
    BEGIN_FNC_DEBUG
    QString query_str = "SELECT id,ctime,cdate FROM Papers WHERE ";
    QHash<QString,QVariant> boundValues;

    bool has_previous = false;
    if( !keyword.isEmpty() )
    {
        query_str += "(title LIKE :fkwrd OR text LIKE :skwrd)";
        has_previous = true;
    }
    if( !startDate.isNull() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "cdate>=:csdate";
        boundValues.insert(":csdate",QDate(1,1,1).daysTo(startDate));
        has_previous = true;
    }
    if( !endDate.isNull() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "cdate<=:cedate";
        boundValues.insert(":cedate",QDate(1,1,1).daysTo(endDate));
        has_previous = true;
    }
    if( !startTime.isNull() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "ctime>=:cstime";
        boundValues.insert(":cstime",QTime(0,0,0).secsTo(startTime));
        has_previous = true;
    }
    if( !endTime.isNull() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "ctime<=:cetime";
        boundValues.insert(":cetime",QTime(0,0,0).secsTo(endTime));
        has_previous = true;
    }
    if( group != -1 )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "grp=:grp";
        boundValues.insert(":grp",group);
        has_previous = true;
    }
    if( !weather.isEmpty() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "weather=:wthr";
        boundValues.insert(":wthr",weather);
        has_previous = true;
    }
    if( geo.isValid() )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += ":llttd<latitude AND latitude<:blttd";
        boundValues.insert(":llttd",geo.y());
        boundValues.insert(":blttd",geo.y()+geo.height());

        query_str += " AND ";

        query_str += ":llntd<longitude AND longitude<:blntd";
        boundValues.insert(":llntd",geo.x());
        boundValues.insert(":blntd",geo.x()+geo.width());

        has_previous = true;
    }
    if( domain != Enums::AllPapers )
    {
        if( has_previous )
            query_str += " AND ";

        query_str += "type=:type";
        switch( domain )
        {
        case Enums::NormalPapers:
            boundValues.insert(":type",static_cast<int>(Enums::Normal));
            break;
        case Enums::ToDoPapers:
            boundValues.insert(":type",static_cast<int>(Enums::ToDo));
            break;

        case Enums::UncompletedTasks:
            query_str += " AND text LIKE :kwd";
            boundValues.insert(":kwd","%- %");
            boundValues.insert(":type",static_cast<int>(Enums::ToDo));
            break;
        case Enums::CompletedTasks:
            query_str += " AND text LIKE :kwd";
            boundValues.insert(":kwd","%* %");
            boundValues.insert(":type",static_cast<int>(Enums::ToDo));
            break;
        }
        has_previous = true;
    }

    END_FNC_DEBUG
    if( !has_previous )
        return QList<int>();

    return searchQuery(query_str,keyword,boundValues);
}
Esempio n. 27
0
void AsyncImageCreator::setCrop(const QRectF &cropRect) {
  d->mCropRect =
      QRect(cropRect.x(), cropRect.y(), cropRect.width(), cropRect.height());
  d->mCropImage = 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);
}
Esempio n. 29
0
void DebugDialog::debug(QString prefix, const QRectF &rect, DebugLevel debug, QObject *ancestor) {
	QString msg = prefix+QString(" rect: x=%1 y=%2 w=%3 h=%4")
		.arg(rect.x()).arg(rect.y()).arg(rect.width()).arg(rect.height());
	DebugDialog::debug(msg,debug,ancestor);
}
Esempio n. 30
0
void CardHostWindow::paintBase(QPainter* painter, bool maximized)
{
    if (maximized) {
        // faster, rectangular blit
        painter->setRenderHint(QPainter::SmoothPixmapTransform, false);
        painter->rotate(m_adjustmentAngle);

        Window::paint(painter, 0, 0);
        painter->rotate(-m_adjustmentAngle);
        painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
    } else {
        // draw with rounded corners
        const QPixmap* pix = acquireScreenPixmap();
        if (pix) {
            QRectF brect = boundingRect();
            QPainterPath paintPath;

                            initializeRoundedCornerStage();

                            painter->setCompositionMode(QPainter::CompositionMode_SourceOver);

            if (m_adjustmentAngle == 90 || m_adjustmentAngle == -90) {
                QRectF rotRect = QRectF(brect.y(), brect.x(), brect.height(), brect.width());
                paintPath.addRoundedRect(rotRect, 25, 25);
            } else {
                paintPath.addRoundedRect(m_boundingRect, 25, 25);
            }

            int originX = brect.x();
            int originY = brect.y();

            if (m_adjustmentAngle == 90 || m_adjustmentAngle == -90) {
                originX = brect.y();
                originY = brect.x();
            }

            if (fullScreen()) {
                if (m_adjustmentAngle == 90 || m_adjustmentAngle == -90) {
                    painter->setBrushOrigin(originX - (pix->width()-brect.height())/2, originY);
                } else {
                    painter->setBrushOrigin(originX, originY - (pix->height() - brect.height()) / 2);
                }
            }
            else
                painter->setBrushOrigin(originX, originY);
                            painter->rotate(m_adjustmentAngle);
#if defined(USE_ROUNDEDCORNER_SHADER)
                            m_roundedCornerShaderStage->setOnPainter(painter);
                            if (m_adjustmentAngle == 90 || m_adjustmentAngle == -90) {
                                painter->drawPixmap(-brect.height()/2, -brect.width()/2, *pix);
                            }
                            else {
                                painter->drawPixmap(-brect.width()/2, -brect.height()/2, *pix);
                            }
                            m_roundedCornerShaderStage->removeFromPainter(painter);
#else
                            painter->fillPath(paintPath, *pix);
#endif
                            painter->rotate(-m_adjustmentAngle);
            painter->setBrushOrigin(0, 0);
        }
    }
}