Esempio n. 1
0
void Player::advance(int step) {

    if (step == 0) {
        // ignore that we are _about_ to advance
        return;
    }

    if (m_left){
        this->setRect(this->rect().translated(QPointF(-10,0)));
    }
    if (m_right){
        this->setRect(this->rect().translated(QPointF(10,0)));
    }
    if (this->rect().right() > scene()->width()){
        qWarning("hit right");
        QRectF newRec =  this->rect();
        newRec.moveLeft(scene()->width() - this->rect().width());
        this->setRect(newRec);
    }
    if (this->rect().left() < 0){
        qWarning("hit right");
        QRectF newRec =  this->rect();
        newRec.moveLeft(0);
        this->setRect(newRec);
    }


}
Esempio n. 2
0
void
FormCheckBox::draw( QPainter * painter, const QPen & pen, const QFont & font,
	const QRectF & rect, qreal width, bool isChecked, const QString & text )
{
	painter->setPen( pen );

	painter->drawRect( rect );

	if( isChecked )
	{
		painter->drawLine( QLineF( rect.topLeft().x() + 4.0,
			rect.topLeft().y() + rect.height() / 2.0,
			rect.topLeft().x() + rect.width() / 2.0,
			rect.bottomLeft().y() - 4.0 ) );

		painter->drawLine( QLineF(
			rect.topLeft().x() + rect.width() / 2.0,
			rect.bottomLeft().y() - 4.0,
			rect.topRight().x() - 4.0,
			rect.topRight().y() + 4.0 ) );
	}

	painter->setFont( font );

	QRectF r = rect;

	r.setRight( rect.x() + width );
	r.moveLeft( rect.x() + rect.height() + 4.0 );

	painter->drawText( r, Qt::AlignLeft | Qt::AlignVCenter, text );
}
Esempio n. 3
0
// slot
void PrintWidget::printAreaMoved()
{
	QRectF area = map_printer->getPrintArea();
	area.moveLeft(left_edit->value());
	area.moveTop(-top_edit->value()); // Flip sign!
	map_printer->setPrintArea(area);
}
Esempio n. 4
0
void EditorView::mouseMoveEvent(QMouseEvent *event)
{
	if (mWheelPressed) {
		if (mMouseOldPosition != QPointF()) {
			QRectF rect = sceneRect();
			qreal dx = (event->posF().x() - mMouseOldPosition.x());
			qreal dy = (event->posF().y() - mMouseOldPosition.y());
			rect.moveLeft(rect.left() - dx);
			rect.moveTop(rect.top() - dy);
			setSceneRect(rect);
		}
		mMouseOldPosition = event->posF();
	}
	QGraphicsView::mouseMoveEvent(event);
	if (event->buttons() & Qt::RightButton) {
		setDragMode(NoDrag);
	} else {
		if (event->buttons() & Qt::LeftButton ) {
			UML::EdgeElement *newEdgeEl = dynamic_cast<UML::EdgeElement *>(itemAt(event->pos()));
			if (newEdgeEl == NULL) {
				setDragMode(RubberBandDrag);
			} else {
				if (newEdgeEl->isBreakPointPressed()) {
					newEdgeEl->breakPointUnpressed();
					setDragMode(NoDrag);
				}
			}
		}
	}
	if (mScene->getNeedDrawGrid())
		mScene->invalidate();
}
Esempio n. 5
0
void EditorView::mouseMoveEvent(QMouseEvent *event)
{
	if (mWheelPressed) {
		if (mMouseOldPosition != QPointF()) {
			QRectF rect = sceneRect();
			qreal dx = (event->localPos().x() - mMouseOldPosition.x());
			qreal dy = (event->localPos().y() - mMouseOldPosition.y());
			rect.moveLeft(rect.left() - dx);
			rect.moveTop(rect.top() - dy);
			setSceneRect(rect);
			translate(dx, dy);
		}
		mMouseOldPosition = event->localPos();
	}
	QGraphicsView::mouseMoveEvent(event);
	if (event->buttons() & Qt::RightButton) {
		setDragMode(NoDrag);
	} else {
		if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ControlModifier)) {
			setDragMode(RubberBandDrag);
			mScene->itemSelectUpdate();
		/*} else 	if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ShiftModifier)) {
			setDragMode(ScrollHandDrag); //  (see #615)
			mScene->itemSelectUpdate();*/
		} else if (event->buttons() & Qt::LeftButton ) {
			EdgeElement *newEdgeEl = dynamic_cast<EdgeElement *>(itemAt(event->pos()));
			if (newEdgeEl && newEdgeEl->isBreakPointPressed()) {
				newEdgeEl->breakPointUnpressed();
				setDragMode(NoDrag);
			}
		}
	}
	if (mScene->getNeedDrawGrid())
		mScene->invalidate();
}
Esempio n. 6
0
QVariant PixmapItem::itemChange(GraphicsItemChange change,
                                const QVariant &value)
{
    if (change == ItemPositionChange)
    {
        // value is the new position.
        QPointF newPos = value.toPointF();
        QRectF rect = parentItem()->boundingRect();

        rect.moveLeft(boundingRect().width()*3/4*-1);
        rect.setWidth(rect.width() + boundingRect().width()*2/4 );

        rect.moveTop(boundingRect().height()*3/4*-1);
        rect.setHeight(rect.height() + boundingRect().height()*2/4 );

        CardItem *card = qgraphicsitem_cast<CardItem *>(parentItem());

        if (!rect.contains(newPos))
        {
            // Keep the item inside the scene rect.
            int newX = (int)qMin(rect.right(), qMax(newPos.x(), rect.left()));
            int newY = (int)qMin(rect.bottom(), qMax(newPos.y(), rect.top()));



            if(card->isAlign())
            {
                int gridSize = card->getGridSize();
                newX = (newX/(10*gridSize))*(10*gridSize);
                newY = (newY/(10*gridSize))*(10*gridSize);
            }

            newPos.setX(newX);
            newPos.setY(newY);
            return newPos;
        }
        else
        {
            int newX =  newPos.x();
            int newY = newPos.y();

            if(card->isAlign())
            {
                int gridSize = card->getGridSize();
                newX = newPos.x()/(10*gridSize);
                newX = newX * (10*gridSize);
                newY = newPos.y()/(10*gridSize);
                newY = newY*(10*gridSize);

            }

            newPos.setX(newX);
            newPos.setY(newY);
            return newPos;

        }
    }

    return QGraphicsItem::itemChange(change, value);
}
Esempio n. 7
0
void ShapeSideBar::onXChanged(int x)
{
	if (d->rectLayer)
	{
		QRectF rect = d->rectLayer->rect();
		rect.moveLeft(x);
		layerScene()->setLayerProperty(d->rectLayer, rect, RoleRect, tr("Change Rectangle x"));
	}
}
Esempio n. 8
0
    void relayoutExtender()
    {
        if (!m_extenders.contains(q->scene())
            || !m_extenders[q->scene()]
            || q != m_extenders[q->scene()]->parentItem()) return;
        QRectF geometry = QRectF(QPointF(0, 0), q->size());

        // extender()->borders = Plasma::FrameSvg::AllBorders;
        borders = Plasma::FrameSvg::AllBorders;

        switch (extenderPosition) {
        case TopExtender:
            geometry.setHeight(EXTENDER_SIZE);
            geometry.moveTop(- EXTENDER_SIZE);
            // borders &= ~ Plasma::FrameSvg::TopBorder;
            // extender()->borders &= ~ Plasma::FrameSvg::BottomBorder;
            break;
        case BottomExtender:
            geometry.moveTop(geometry.bottom());
            geometry.setHeight(EXTENDER_SIZE);
            // borders &= ~ Plasma::FrameSvg::BottomBorder;
            // extender()->borders &= ~ Plasma::FrameSvg::TopBorder;
            break;
        case LeftExtender:
            geometry.setWidth(EXTENDER_SIZE);
            geometry.moveLeft(- EXTENDER_SIZE);
            // borders &= ~ Plasma::FrameSvg::LeftBorder;
            // extender()->borders &= ~ Plasma::FrameSvg::RightBorder;
            break;
        case RightExtender:
            geometry.moveLeft(geometry.right());
            geometry.setWidth(EXTENDER_SIZE);
            // borders &= ~ Plasma::FrameSvg::RightBorder;
            // extender()->borders &= ~ Plasma::FrameSvg::LeftBorder;
            break;
        case NoExtender:
            break;
        }
        extender()->setGeometry(geometry);
        extender()->setPreferredSize(geometry.size());

        // qreal left, top, right, bottom;
        // q->getContentsMargins(&left, &top, &right, &bottom);
    }
Esempio n. 9
0
// QtPluginIconPalletTool Interface
void
dmz::QtPluginIconPalletTool::_add_type (const ObjectType &Type) {

   const String IconResource = config_to_string (
      get_plugin_name () + ".resource",
      Type.get_config());

   const String IconName = _rc.find_file (IconResource);

   if (IconName) {

      const String Name = Type.get_name ();

      if (Name) {

         QImage back (
            (int)_iconExtent,
            (int)_iconExtent,
            QImage::Format_ARGB32_Premultiplied);
         QPainter painter (&back);
         painter.setCompositionMode (QPainter::CompositionMode_Source);
         painter.fillRect (back.rect (), Qt::transparent);
         painter.setCompositionMode (QPainter::CompositionMode_SourceOver);
         QSvgRenderer qsr (QString (IconName.get_buffer ()));
         QRectF size = qsr.viewBoxF ();
         qreal width = size.width ();
         qreal height = size.height ();
         qreal scale = (width > height) ? width : height;
         if (scale <= 0.0f) { scale = 1.0f; }
         scale = _iconExtent / scale;
         width *= scale;
         height *= scale;
         size.setWidth (width);
         size.setHeight (height);
         if (height < _iconExtent) { size.moveTop ((_iconExtent - height) * 0.5f); }
         if (width < _iconExtent) { size.moveLeft ((_iconExtent - width) * 0.5f); }
         qsr.render (&painter, size);
         painter.end ();
         QIcon icon;
         icon.addPixmap (QPixmap::fromImage (back));
         QStandardItem *item = new QStandardItem (icon, Name.get_buffer ());
         item->setEditable (false);
         _model.appendRow (item);
      }
   }
   else if (IconResource) {

      _log.error << "Unable to find icon resource: " << IconResource
          << " for object type: " << Type.get_name () << endl;
   }

   RuntimeIterator it;
   ObjectType next;

   while (Type.get_next_child (it, next)) { _add_type (next); }
}
Esempio n. 10
0
void GraphNode::setCenter(const QPointF& pt)
{
    cx = pt.x();
    cy = pt.y();

    QRectF newRect = rect();
    newRect.moveLeft(cx - r);
    newRect.moveTop(cy - r);
    setRect(newRect);
}
    foreach(QReportWidgetBase  *widget, _selectedWidgets) {
        QRectF widgetRect = _widgetRects[widget];
        QSizeF sizeby(
            rc.width()  / selectionRect.width(),
            rc.height() / selectionRect.height());

        widgetRect.moveTop(widgetRect.top()  - selectionRect.top());
        widgetRect.moveLeft(widgetRect.left() - selectionRect.left());

        widgetRect.setTop(widgetRect.top()     *sizeby.height());
        widgetRect.setBottom(widgetRect.bottom()  *sizeby.height());
        widgetRect.setLeft(widgetRect.left()    *sizeby.width());
        widgetRect.setRight(widgetRect.right()   *sizeby.width());

        widgetRect.moveTop(widgetRect.top()  + rc.top());
        widgetRect.moveLeft(widgetRect.left() + rc.left());

        widgetRect.moveTopLeft(widget->parentItem()->mapFromScene(widgetRect.topLeft()));

        widget->setPos(widgetRect.topLeft());
        widget->setSize(widgetRect.width(), widgetRect.height());

    }
Esempio n. 12
0
QList<QRectF> Mode1::locate()
{
	QList<QRectF> results;
	if (rect.height() > 360){
		return results;
	}
	QSize size = ARender::instance()->getActualSize();
	QRectF init = rect;
	init.moveLeft(size.width());
	int end = size.height()*(Config::getValue("/Danmaku/Protect", false) ? 0.85 : 1) - rect.height();
	int stp = Config::getValue("/Danmaku/Grating", 10);
	for (int height = 0; height <= end; height += stp){
		init.moveTop(height);
		results.append(init);
	}
	return results;
}
//-----------------------------------------------------------------------------
QRectF vktraceviewer_QTimelineView::viewportRect(const QModelIndex &index) const
{
    QRectF rectf = itemRect(index);
    if (rectf.isValid())
    {
        rectf.moveLeft( rectf.left() * m_zoomFactor);
        rectf.setWidth( rectf.width() * m_zoomFactor);

        rectf.adjust(-horizontalScrollBar()->value(), 0,
                     -horizontalScrollBar()->value(), 0);

        // the margin is added last so that it is NOT scaled
        rectf.adjust(m_margin, 0,
                     m_margin, 0);
    }

    return rectf;
}
Esempio n. 14
0
    void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
    {
        FullScreenTheme::RenderInfo info = FullScreenTheme::renderInfo(FullScreenTheme::CountDownWidget);
        painter->setRenderHint(QPainter::Antialiasing);
        const int circle = 5760;
        const int start = circle / 4; // Start at 12h, not 3h
        const int end = int(circle * mValue);
        painter->setBrush(info.bgBrush);
        painter->setPen(info.borderPen);

        QRectF square = boundingRect().adjusted(.5, .5, -.5, -.5);
        qreal width = square.width();
        qreal height = square.height();
        if (width < height) {
            square.setHeight(width);
            square.moveTop((height - width) / 2);
        } else {
            square.setWidth(height);
            square.moveLeft((width - height) / 2);
        }
        painter->drawPie(square, start, end);
    }
Esempio n. 15
0
QRectF PrintJob::preparePage(int pageNumber)
{
    int sheetPageNumber = pageNumber;
    Sheet* sheet = d->getSheetPageNumber(&sheetPageNumber);
    if (!sheet)
        return QRectF();

    // Move the painter offset according to the page layout.
    const double scale = POINT_TO_INCH(printer().resolution());
    const KoPageLayout pageLayout = sheet->printSettings()->pageLayout();
    painter().translate(pageLayout.left * scale, pageLayout.top * scale);

    // Apply the print zoom factor,
    const double zoom = d->printManager(sheet)->zoom();
    painter().scale(zoom, zoom);

    // Prepare the page for shape printing.
    const QRect cellRange = d->printManager(sheet)->cellRange(sheetPageNumber);
    QRectF pageRect = sheet->cellCoordinatesToDocument(cellRange);
    painter().translate(-pageRect.left() * scale, -pageRect.top() * scale);

    // Center the table on the page.
    if (sheet->printSettings()->centerHorizontally())
    {
        const double printWidth = sheet->printSettings()->printWidth(); // FIXME respect repeated columns
        const double offset = 0.5 * (printWidth / zoom - pageRect.width());
        painter().translate(offset * scale, 0.0);
        pageRect.moveLeft(offset); // scale will be applied below
    }
    if (sheet->printSettings()->centerVertically())
    {
        const double printHeight = sheet->printSettings()->printHeight(); // FIXME respect repeated rows
        const double offset = 0.5 * (printHeight / zoom - pageRect.height());
        painter().translate(0.0, offset * scale);
        pageRect.moveTop(offset); // scale will be applied below
    }
    return QRectF(pageRect.left() * scale, pageRect.top() * scale,
        pageRect.width() * scale, pageRect.height() * scale);
}
Esempio n. 16
0
void QWaterfallWidget::__drawWaterfall(QPainter &painter)
{
    float widthF = (float)rect().width() / m_columns;
    float heightF = (float)rect().height() / m_rows;
    float posX = 0.0, posY = 0.0;
    QRectF rectF = QRectF(0.0, 0.0, widthF, heightF);
    painter.setPen(Qt::NoPen);
    int temp;
    for(int i = 0; i < m_rows; i++) {
        rectF.moveTop(posY);
        posX = 0.0;
        for(int j = 0; j < m_columns; j++) {
                rectF.moveLeft(posX);
                temp = m_data[i][j]*1023;
                temp = (temp > 1023) ? 1023 : temp;
                temp = (temp < 0) ? 0 : temp;
                painter.setBrush(v_lookupTable[temp]);
                painter.drawRect(rectF);
                posX += widthF;
            }
        posY += heightF;
    }
}
Esempio n. 17
0
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 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);
}
Esempio n. 19
0
void overlayStatistics(QImage *image)
{
	QPainter p(image);

	QString stats;

	stats = "LuxRender " + QString::fromLatin1(luxVersion()) + " ";
	stats += "|Saved: " + QDateTime::currentDateTime().toString(Qt::DefaultLocaleShortDate) + " ";

	QString rendererStats = getStringAttribute("renderer_statistics_formatted", "_recommended_string");
	// fallback statistics
	if (rendererStats.isEmpty())	// if no renderer stats available
	{
		int pixels = luxGetIntAttribute("film", "xResolution") * luxGetIntAttribute("film", "yResolution");
		double spp = luxGetDoubleAttribute("film", "numberOfResumedSamples") / pixels;

		rendererStats = QString("%1 %2S/p").arg(luxMagnitudeReduce(spp), 0, 'f', 2).arg(luxMagnitudePrefix(spp));
	}
	stats += "|Statistics: " + rendererStats + " ";

	// convert regular spaces to non-breaking spaces, so that it will prefer to wrap
	// between segments
	stats = stats.replace(QChar(' '), QChar::Nbsp);
	stats = stats.replace("|", " |  ");

#if defined(__APPLE__)
	QFont font("Monaco");
#else
	QFont font("Helvetica");
#endif
	font.setStyleHint(QFont::SansSerif, static_cast<QFont::StyleStrategy>(QFont::PreferAntialias | QFont::PreferQuality));
	
	int fontSize = (int)min(max(image->width() / 100.0f, 10.f), 18.f);
	font.setPixelSize(fontSize);

	QFontMetrics fontMetrics(font);
	int leading = fontMetrics.leading();

	QTextLayout textLayout(stats, font, image);

	QTextOption textOption;
	//textOption.setUseDesignMetrics(true);
	textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
	textOption.setAlignment(Qt::AlignLeft);
	textLayout.setTextOption(textOption);

	textLayout.beginLayout();
	QTextLine line;
	qreal height = leading;
	qreal maxwidth = image->width() - 10;
	while ((line = textLayout.createLine()).isValid()) {
		line.setLineWidth(maxwidth);
		height += leading;
		line.setPosition(QPointF(0, height));
		height += line.height();
	}
	height += 2*leading;
	textLayout.endLayout();

	QRectF rect = textLayout.boundingRect();
	rect.setHeight(height);

	// align at bottom
	rect.moveLeft((image->width() - maxwidth) / 2.f);
	rect.moveTop(image->height() - rect.height());

	// darken background
	p.setOpacity(0.6);
	p.fillRect(0, rect.top(), image->width(), rect.height(), Qt::black);

	// draw text
	p.setOpacity(1.0);
	p.setPen(QColor(240, 240, 240));
	textLayout.draw(&p, rect.topLeft());

	p.end();
}
Esempio n. 20
0
void PanelAppletOverlay::mouseMoveEvent(QMouseEvent *event)
{
    if (!m_layout || !m_applet) {
        //kDebug() << "no layout";
        return;
    }

    const int margin = 9;
    if (m_applet->inherits("PanelSpacer")) {
        if (m_applet->formFactor() == Plasma::Horizontal) {
            if (event->pos().x() < margin || event->pos().x() > m_applet->size().width() - margin) {
                setCursor(Qt::SizeHorCursor);
            } else {
                setCursor(Qt::ArrowCursor);
            }
        } else if (m_applet->formFactor() == Plasma::Vertical) {
            if (event->pos().y() < margin || event->pos().y() > m_applet->size().height() - margin) {
                setCursor(Qt::SizeVerCursor);
            } else {
                setCursor(Qt::ArrowCursor);
            }
        }
    }

    if (!m_clickDrag && !(event->buttons() & Qt::LeftButton)) {
        //kDebug() << "no left button and we aren't click dragging";
        return;
    }

    Plasma::FormFactor f = m_applet->formFactor();


    if (!m_applet->inherits("PanelSpacer") &&
          (((f != Plasma::Horizontal && f != Plasma::Vertical) && rect().intersects(m_applet->rect().toRect())) ||
          ((f == Plasma::Horizontal || f == Plasma::Vertical) && !rect().contains(event->globalPos()))) ) {
        Plasma::View *view = Plasma::View::topLevelViewAt(event->globalPos());
        //kDebug() << "checking view" << view << m_applet->view();

        if (!view) {
            view = dynamic_cast<Plasma::View*>(parent());
        }

        if (!view) {
            return;
        }

        if (view != m_applet->view() && (event->buttons() & Qt::LeftButton)) {
            Plasma::Containment *c = view->containment();
            if (!c) {
                return;
            }

            syncOrientation();
            syncGeometry();

            if (m_spacer) {
                if (m_layout) {
                    m_layout->removeItem(m_spacer);
                }
                m_spacer->deleteLater();
                m_spacer = 0;
            }

            QPointF pos = c->view()->mapFromGlobal(event->globalPos());
            QRectF g = m_applet->geometry();
            pos += QPoint(m_offset, m_offset);
            g.moveTo(pos);
            m_applet->setGeometry(g);
            m_layout = 0;
            c->addApplet(m_applet, pos, true);
            m_applet->flushPendingConstraintsEvents();
            m_applet->setPos(pos);
            releaseMouse();
            emit moved(this);
            return;
        }
    } else if (m_applet->inherits("PanelSpacer") && m_dragAction != Move) {
        if (m_applet->formFactor() == Plasma::Horizontal) {
            if (m_dragAction == LeftResize) {
                int fixedWidth = m_applet->size().width()+(m_lastGlobalPos.x() - event->globalPos().x());
                m_applet->setPos(m_applet->pos().x()-(fixedWidth-m_applet->size().width()), m_applet->pos().y());
                m_applet->setMinimumWidth(fixedWidth);
                m_applet->setMaximumWidth(fixedWidth);
            } else if (m_dragAction == RightResize) {
                int fixedWidth = m_applet->size().width()-(m_lastGlobalPos.x() - event->globalPos().x());
                m_applet->setMinimumWidth(fixedWidth);
                m_applet->setMaximumWidth(fixedWidth);
            }
        } else if (m_applet->formFactor() == Plasma::Vertical) {
            if (m_dragAction == LeftResize) {
                int fixedHeight = m_applet->size().height()+(m_lastGlobalPos.y() - event->globalPos().y());
                m_applet->setPos(m_applet->pos().x(), m_applet->pos().y()-(fixedHeight-m_applet->size().height()));
                m_applet->setMinimumHeight(fixedHeight);
                m_applet->setMaximumHeight(fixedHeight);
            } else if (m_dragAction == RightResize) {
                int fixedHeight = m_applet->size().height()-(m_lastGlobalPos.y() - event->globalPos().y());
                m_applet->setMinimumHeight(fixedHeight);
                m_applet->setMaximumHeight(fixedHeight);
            }
        }
        m_lastGlobalPos = event->globalPos();
        return;
    }

    if (!m_spacer) {
        m_spacer = new AppletMoveSpacer(m_applet);
        m_spacer->setMinimumSize(m_applet->geometry().size());
        m_spacer->setMaximumSize(m_applet->geometry().size());
        if (m_layout) {
            m_layout->removeItem(m_applet);
            m_layout->insertItem(m_index, m_spacer);
        }
    }

    QPoint p = mapToParent(event->pos());
    QRectF g = m_applet->geometry();

    //kDebug() << p << g << "<-- movin'?";
    if (m_orientation == Qt::Horizontal) {
        g.moveLeft(p.x() + m_offset);
    } else {
        g.moveTop(p.y() + m_offset);
    }

    m_applet->setGeometry(g);

    //FIXME: assumption on how panel containment works, presence of a non applet spacer in last position (if they were swapped would be impossible to save and restore)
    if ((m_index > 0 && m_layout->itemAt(m_index - 1)) || m_index == 0) {
        const bool prevIsApplet = dynamic_cast<Plasma::Applet*>(m_layout->itemAt(m_index - 1)) != 0;
        const bool nextIsApplet = dynamic_cast<Plasma::Applet*>(m_layout->itemAt(m_index + 1)) != 0;

        QPointF mousePos = event->pos() + g.topLeft();

        // swap items if we pass completely over the next/previous item or cross
        // more than halfway across it, whichever comes first
        if (m_orientation == Qt::Horizontal) {
            //kDebug() << prevIsApplet << m_prevGeom << g << nextIsApplet << m_nextGeom;
            if (QApplication::layoutDirection() == Qt::RightToLeft) {
                if (prevIsApplet && m_prevGeom.isValid() && mousePos.x() >= m_prevGeom.right()) {
                    swapWithPrevious();
                } else if (nextIsApplet && m_nextGeom.isValid() && mousePos.x() <= m_nextGeom.left()) {
                    swapWithNext();
                }
            } else if (prevIsApplet && m_prevGeom.isValid() && mousePos.x() <= m_prevGeom.left()) {
                swapWithPrevious();
            } else if (nextIsApplet && m_nextGeom.isValid() && mousePos.x() >= m_nextGeom.right()) {
                swapWithNext();
            }

        } else if (prevIsApplet && m_prevGeom.isValid() && mousePos.y() <= m_prevGeom.top()) {
            swapWithPrevious();
        } else if (nextIsApplet && m_nextGeom.isValid() && mousePos.y() >= m_nextGeom.bottom()) {
            swapWithNext();
        }
    }

    m_lastGlobalPos = event->globalPos();
    //kDebug() << "=================================";
}
Esempio n. 21
0
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);
  }
}
Esempio n. 22
0
void PrintWidget::centerOnMap(QRectF& area) const
{
	QRectF map_extent = map->calculateExtent(false, show_templates_check->isChecked(), main_view);
	area.moveLeft(map_extent.center().x() - 0.5f * area.width());
	area.moveTop(map_extent.center().y() - 0.5f * area.height());
}
Esempio n. 23
0
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;
  double spacing, width, yscale;

  spacing = elastic ? (double) bounds.width() / count : thumbSize.width() + gap;
  width = elastic ? qMin( spacing, (double) 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 );
    }
  }

  p.setPen( strokeColor() );

  // 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));
      }
    }
  }
}
Esempio n. 24
0
void Clock::paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
    Q_UNUSED(option);

    if (!m_time.isValid() || !m_date.isValid()) {
        return;
    }

    p->setPen(QPen(m_plainClockColor));
    p->setRenderHint(QPainter::SmoothPixmapTransform);
    p->setRenderHint(QPainter::Antialiasing);

    /* ... helps debugging contentsRect and sizing ...
       QColor c = QColor(Qt::blue);
       c.setAlphaF(.5);
       p->setBrush(c);
       p->drawRect(contentsRect);
     */

    // Paint the date, conditionally, and let us know afterwards how much
    // space is left for painting the time on top of it.
    QRectF dateRect;
    const QString timeString = KGlobal::locale()->formatTime(m_time, m_showSeconds);
    const QString fakeTimeString = KGlobal::locale()->formatTime(QTime(23,59,59), m_showSeconds);
    QFont smallFont = KGlobalSettings::smallestReadableFont();

    //create the string for the date and/or the timezone
    if (m_dateStyle || showTimezone()) {
        QString dateString;

        //Create the localized date string if needed
        if (m_dateStyle) {
            // JPL This needs a complete rewrite for l10n issues
            QString day = KGlobal::locale()->calendar()->formatDate(m_date, KLocale::Day, KLocale::ShortNumber);
            QString month = KGlobal::locale()->calendar()->formatDate(m_date, KLocale::Month, KLocale::LongNumber);

            if (m_dateStyle == 1) {         //compact date
                dateString = i18nc("@label Compact date: "
                        "%1 day in the month, %2 month number",
                        "%1/%2", day, month);
            } else if (m_dateStyle == 2) {    //short date
                dateString = KGlobal::locale()->formatDate(m_date, KLocale::ShortDate);
            } else if (m_dateStyle == 3) {    //long date
                dateString = KGlobal::locale()->formatDate(m_date, KLocale::LongDate);
            } else if (m_dateStyle == 4) {    //ISO date
                dateString = KGlobal::locale()->formatDate(m_date, KLocale::IsoDate);
            } else {                          //shouldn't happen
                dateString = KGlobal::locale()->formatDate(m_date, KLocale::ShortDate);
            }

            if (showTimezone()) {
                QString currentTimezone = prettyTimezone();
                dateString = i18nc("@label Date with currentTimezone: "
                        "%1 day of the week with date, %2 currentTimezone",
                        "%1 %2", dateString, currentTimezone);
            }
        } else if (showTimezone()) {
            dateString = prettyTimezone();
        }

        dateString = dateString.trimmed();

        if (m_dateString != dateString) {
            // If this string has changed (for example due to changes in the config
            // we have to reset the sizing of the applet
            m_dateString = dateString;
            updateSize();
        }

        // Check sizes
        // magic 10 is for very big spaces,
        // where there's enough space to grow without harming time space
        QFontMetrics fm(smallFont);

        if (contentsRect.height() > contentsRect.width() * 2) {
            //kDebug() << Plasma::Vertical << contentsRect.height() <<contentsRect.width() * 2;
            QRect dateRect = contentsRect;
            dateRect.setHeight(dateRect.width());
            smallFont.setPixelSize(qMax(dateRect.height() / 2, fm.ascent()));
            m_dateRect = preparePainter(p, dateRect, smallFont, dateString);
        } else {
            // Find a suitable size for the date font
            if (formFactor() == Plasma::Vertical) {
                smallFont.setPixelSize(qMax(contentsRect.height()/6, fm.ascent()));
            } else if (formFactor() == Plasma::Horizontal) {
                smallFont.setPixelSize(qMax(qMin(contentsRect.height(), contentsRect.width())*2/7, fm.ascent()));

                //we want to write the date always on one line
                fm = QFontMetrics(smallFont);
                const int tempWidth = fm.width(dateString);
                if(tempWidth > contentsRect.width()){
                    smallFont.setPixelSize((contentsRect.width() * smallFont.pixelSize())/tempWidth);
                }

            } else {
                smallFont.setPixelSize(qMax(qMin(contentsRect.height(), contentsRect.width())/8, KGlobalSettings::smallestReadableFont().pointSize()));
            }

            m_dateRect = preparePainter(p, contentsRect, smallFont, dateString);
        }

        // kDebug(96669) << "m_dateRect: " << m_dateRect;

        const int subtitleHeight = m_dateRect.height();
        const int subtitleWidth = m_dateRect.width();
        // kDebug(96669) << "subtitleWitdh: " << subtitleWitdh;
        // kDebug(96669) << "subtitleHeight: " << subtitleHeight;

        if (m_dateTimezoneBesides) {
            //kDebug(96669) << contentsRect.height() << subtitleHeight << smallFont.pixelSize();
            if (contentsRect.height() - subtitleHeight >= smallFont.pixelSize() || formFactor() != Plasma::Horizontal) {
                // to small to display the time on top of the date/timezone
                // put them side by side
                // kDebug(96669) << "switching to normal";
                m_dateTimezoneBesides = false;
                dateRect = normalLayout(subtitleWidth, subtitleHeight, contentsRect);
            } else {
                dateRect = sideBySideLayout(subtitleWidth, subtitleHeight, contentsRect);
            }
        } else {
            /* kDebug(96669) << "checking timezone placement"
                          << contentsRect.height() << dateRect.height() << subtitleHeight
                          << smallFont.pixelSize() << smallFont.pointSize();*/
            if (contentsRect.height() - subtitleHeight < smallFont.pixelSize() && formFactor() == Plasma::Horizontal) {
                // to small to display the time on top of the date/timezone
                // put them side by side
                // kDebug(96669) << "switching to s-b-s";
                m_dateTimezoneBesides = true;
                dateRect = sideBySideLayout(subtitleWidth, subtitleHeight, contentsRect);
            } else {
                dateRect = normalLayout(subtitleWidth, subtitleHeight, contentsRect);
            }
        }
    } else {
        m_timeRect = contentsRect;
    }
    // kDebug(96669) << "timeRect: " << m_timeRect;
    // p->fillRect(timeRect, QBrush(QColor("red")));

    // kDebug(96669) << m_time;
    // Choose a relatively big font size to start with
    m_plainClockFont.setPointSizeF(qMax(m_timeRect.height(), KGlobalSettings::smallestReadableFont().pointSize()));
    preparePainter(p, m_timeRect, m_plainClockFont, fakeTimeString, true);

    if (!m_dateString.isEmpty()) {
        if (m_dateTimezoneBesides) {
            QFontMetrics fm(m_plainClockFont);
            //kDebug() << dateRect << m_timeRect << fm.boundingRect(m_timeRect, Qt::AlignCenter, timeString);
            QRect br = fm.boundingRect(m_timeRect, Qt::AlignCenter, timeString);

            QFontMetrics smallfm(smallFont);
            dateRect.moveLeft(br.right() + qMin(0, br.left()) + smallfm.width(" "));
        }

        // When we're relatively low, force everything into a single line
        QFont f = p->font();
        p->setFont(smallFont);

        QPen datePen = p->pen();
        QColor dateColor = m_plainClockColor;
        dateColor.setAlphaF(0.7);
        datePen.setColor(dateColor);
        p->setPen(datePen);

        if (formFactor() == Plasma::Horizontal && (contentsRect.height() < smallFont.pointSize()*6)) {
            p->drawText(dateRect, Qt::TextSingleLine | Qt::AlignHCenter, m_dateString);
        } else {
            p->drawText(dateRect, Qt::TextWordWrap | Qt::AlignHCenter, m_dateString);
        }

        p->setFont(f);
    }

    if (m_useCustomColor || !m_svgExistsInTheme) {
        QFontMetrics fm(p->font());

        QPointF timeTextOrigin(QPointF(qMax(0, (m_timeRect.center().x() - fm.width(fakeTimeString) / 2)),
                            (m_timeRect.center().y() + fm.height() / 3)));
        p->translate(-0.5, -0.5);

        if (m_drawShadow) {
            QPen tmpPen = p->pen();

            // Paint a backdrop behind the time's text
            qreal shadowOffset = 1.0;
            QPen shadowPen;
            QColor shadowColor = m_plainClockShadowColor;
            shadowColor.setAlphaF(.4);
            shadowPen.setColor(shadowColor);
            p->setPen(shadowPen);
            QPointF shadowTimeTextOrigin = QPointF(timeTextOrigin.x() + shadowOffset,
                                                timeTextOrigin.y() + shadowOffset);
            p->drawText(shadowTimeTextOrigin, timeString);

            p->setPen(tmpPen);

            // Paint the time itself with a linear translucency gradient
            QLinearGradient gradient = QLinearGradient(QPointF(0, 0), QPointF(0, fm.height()));

            QColor startColor = m_plainClockColor;
            startColor.setAlphaF(.95);
            QColor stopColor = m_plainClockColor;
            stopColor.setAlphaF(.7);

            gradient.setColorAt(0.0, startColor);
            gradient.setColorAt(0.5, stopColor);
            gradient.setColorAt(1.0, startColor);
            QBrush gradientBrush(gradient);

            QPen gradientPen(gradientBrush, tmpPen.width());
            p->setPen(gradientPen);
        }
        p->drawText(timeTextOrigin, timeString);
    //when use the custom theme colors, draw the time textured
    } else {
        QRect adjustedTimeRect = m_pixmap.rect();
        adjustedTimeRect.moveCenter(m_timeRect.center());
        p->drawPixmap(adjustedTimeRect, m_pixmap);
    }
}
Esempio n. 25
0
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;
}