void QColorTabWidget::drawTab( QPainter& p, QRect& rectTab, const TabInfo& ti, bool bHover, bool bActive, bool bNotify )
{
    QPainterPath tabPath;
    QPainterPath tabS;

    int nDiameter = 3 << 1;
    QRectF arcRect( 0, 0, nDiameter, nDiameter );

    if (isHorzTab())
    {
        // Horz-Tab
        tabPath.moveTo( rectTab.bottomLeft() );
        tabPath.lineTo( rectTab.left(), rectTab.top()+nDiameter/2);
        tabS.moveTo( rectTab.left(), rectTab.top()+nDiameter/2 );
        arcRect.moveTo( rectTab.topLeft() );
        tabPath.arcTo( arcRect, 180, -90 );
        tabS.arcTo( arcRect, 180, -90 );
        tabPath.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
        tabS.lineTo( rectTab.right()-nDiameter/2, rectTab.top() );
        arcRect.moveTo( rectTab.right()-nDiameter, rectTab.top() );
        tabPath.arcTo( arcRect, 90, -90 );
        tabS.arcTo( arcRect, 90, -90 );
        tabPath.lineTo( rectTab.bottomRight() );
        tabS.closeSubpath();
        //tabPath.closeSubpath();
    }
    else
    {
        // Vert-Tab
        tabPath.moveTo( rectTab.right(), rectTab.y() );
        tabPath.lineTo( rectTab.x()+nDiameter, rectTab.y() );
        tabS.moveTo( rectTab.x()+nDiameter, rectTab.y() );
        arcRect.moveTo(rectTab.topLeft());
        tabPath.arcTo( arcRect, -270, 90 );
        tabS.arcTo( arcRect, -270, 90 );
        arcRect.moveTo(rectTab.x(), rectTab.bottom()-nDiameter);
        tabPath.arcTo( arcRect, -180, 90 );
        tabS.arcTo( arcRect, -180, 90 );
        tabPath.moveTo( rectTab.left()+nDiameter, rectTab.bottom() );
        tabPath.lineTo( rectTab.right(), rectTab.bottom() );
        tabS.closeSubpath();
        //tabPath.closeSubpath();
    }

    QColor colorBody;

    if (bNotify && (m_nBlinkCount % 2 == 0))
    {
        colorBody = QColor(252, 209, 211);
    }
    else
    {
        if (bActive)
            colorBody = QColor(255, 255, 255);
        else
            colorBody = QColor(0xF5, 0xF5, 0xF5);
    }

    p.fillPath( tabPath, QBrush(colorBody) );

    QColor colorStart = bActive ? ti.clrTab : (bHover ? QColor(255, 190, 60, 200) : QColor(255, 255, 255, 200));
    QColor colorEnd(255, 255, 255, 200);
    QRectF rectTabTip;
    rectTabTip = tabS.boundingRect();
    QLinearGradient gradTip;
    if (!isHorzTab())
    {
        gradTip.setStart(rectTabTip.left(), rectTabTip.center().y());
        gradTip.setFinalStop(rectTabTip.right(), rectTabTip.center().y());
    }
    else
    {
        gradTip.setStart(rectTabTip.center().x(), rectTabTip.top());
        gradTip.setFinalStop(rectTabTip.center().x(), rectTabTip.bottom());
    }
    gradTip.setColorAt( 0, colorStart );
    gradTip.setColorAt( 1.f, colorEnd );

    p.setBrush(Qt::NoBrush);
    p.setPen( QPen(QColor(160,160,160,100), 2.f) );
    p.drawPath( tabPath );
    p.setPen( QPen(QColor(160,160,160)) );
    p.drawPath( tabPath );

    p.fillPath( tabS, QBrush(gradTip) );
    if (bActive || bHover)
    {
        p.setPen( colorStart );
        p.drawPath( tabS );
    }

    QRectF rectText;

    float fTextOffset = ti.pIconImage ? ti.pIconImage->width()+5.f : 0.f;

    if (isHorzTab())
    {
        rectText.setX((float)rectTab.x() + fTextOffset);
        rectText.setY((float)rectTab.y() + nDiameter/2);
        rectText.setWidth((float)rectTab.width() - fTextOffset);
        rectText.setHeight((float)rectTab.height() - nDiameter/2);
    }
    else
    {
        rectText.setX((float)rectTab.x() + nDiameter/2 + fTextOffset);
        rectText.setY((float)rectTab.y());
        rectText.setWidth((float)rectTab.width() - nDiameter/2 - fTextOffset);
        rectText.setHeight((float)rectTab.height());
    }

    m_fntTab.setBold(bActive);

    p.setFont( m_fntTab );

    if (ti.pIconImage)
    {
        int nIW = ti.pIconImage->width();
        int nIH = ti.pIconImage->height();
        p.drawImage( (int)(rectText.x()-fTextOffset), (int)(rectText.y()), *ti.pIconImage, 0, 0, nIW, nIH );
    }

    int flags = Qt::AlignCenter|Qt::AlignVCenter|Qt::TextSingleLine;
    p.setPen( QColor(80,80,80) );
    p.drawText( rectText, flags, ti.strCaption );
}
Example #2
0
void CScreenShotView::mouseMoveEvent(QMouseEvent *event)
{
    if(m_isLocked)
    {
        event->accept();
        return;
    }
    if((event->buttons() & Qt::LeftButton) && m_isPressed)
    {
        m_selectRectItem->setVisible(true);
        m_endPoint = event->pos();
        QPointF startPoint = getPointToSelectedItem(m_startPoint);
        QPointF endPoint = getPointToSelectedItem(event->pos());
        QPointF maxPoint = getPointToSelectedItem(QPointF(this->geometry().width(),this->geometry().height()));
        if(m_shotStatus == CSCREEN_SHOT_STATE_INITIALIZED)
        {
            if(endPoint.x() > maxPoint.x())
            {
                endPoint.setX(maxPoint.x());
            }
            if(endPoint.y() > maxPoint.y())
            {
                endPoint.setY(maxPoint.y());
            }
            if(endPoint.x() < 0)
            {
                endPoint.setX(0);
            }
            if(endPoint.y() < 0)
            {
                endPoint.setY(0);
            }
            //            QRectF rect = getPositiveRect(startPoint,endPoint);
            QRectF rect = CScreenshotUtil::convertLineFToRectF(QLineF(startPoint,endPoint));
            m_selectRectItem->setSelectedRect(rect);
            updateTooltipItem();
        }
        else if(m_shotStatus == CSCREEN_SHOT_STATE_SELECTED)
        {
            updateSelectRect(startPoint,endPoint);
        }
        else if(m_shotStatus == CSCREEN_SHOT_STATE_EDITED && m_currentRectItem)
        {
            //            QRectF rect = getPositiveRect(m_startPoint,event->pos());
            //            QRectF rect = CScreenshotUtil::convertLineFToRectF(QLineF(m_startPoint,event->pos()));
            //            m_currentRectItem->setPainterRect(rect);
            m_currentRectItem->setPainterLine(QLine(m_startPoint,event->pos()));
            m_currentRectItem->setVisible(true);
        }
    }
    if(m_shotStatus == CSCREEN_SHOT_STATE_INITIALIZED)
    {
        updatePreviewItem(event->pos());
        if(!m_isPressed && !m_windowRectList.isEmpty())
        {
            QRect rect = getMouseOnWindowRect(event->globalPos());
            QPoint startPoint = m_desktopScreen->geometry().topLeft();
            QPointF topLeft = getPointToSelectedItem(rect.topLeft() - startPoint);
            QPointF bottomRight = getPointToSelectedItem(rect.bottomRight() - startPoint);
            QRectF selectRect(topLeft,bottomRight);
            if(selectRect.isValid())
            {
                m_selectRectItem->setVisible(true);
                m_selectRectItem->setSelectedRect(selectRect);
            }
        }
    }

    updateCursor(getPointToSelectedItem(event->pos()));
    return QGraphicsView::mouseMoveEvent(event);
}
Example #3
0
void Storage::paintEvent(QPaintEvent *anEvent)
{
    QLabel::paintEvent(anEvent);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    //painter.setRenderHint(QPainter::SmoothPixmapTransform);
    QPen pen;

    if (NoTool != tool_) {
        pen.setWidth(5);
        pen.setColor(QColor(Qt::white));
        pen.setStyle(Qt::DashLine);
        painter.setPen(pen);

        if (BoundingBoxTool == tool_) {
            /* с учётом масштаба */
            QRect bbox = rect.getCoordinates();
            QPoint bboxTopLeft = bbox.topLeft() * scale_;
            QPoint bboxBottomRight = bbox.bottomRight() * scale_;

            bbox.setTopLeft(bboxTopLeft);
            bbox.setBottomRight(bboxBottomRight);

            painter.drawRect(bbox);
        }
        else if (EllipseTool == tool_) {
            /* с учётом масштаба */
            QRect elli = ell.getCoordinates().normalized();
            QPoint ellTopLeft = elli.topLeft() * scale_;
            QPoint ellBottomRight = elli.bottomRight() * scale_;

            elli.setTopLeft(ellTopLeft);
            elli.setBottomRight(ellBottomRight);

            if(1 < elli.height() && 1 < elli.width() )
            {
                painter.drawEllipse(elli);
            }
//            painter.drawRect(ell);
        }
        else if (ArrowTool == tool_) {
            /* с учётом масштаба */
            QLineF line = arrow.getCoordinates();
            QPointF p1 = line.p1() * scale_;
            QPointF p2 = line.p2() * scale_;

            line.setP1(p1);
            line.setP2(p2);

            if(1 < line.length())
            {
                double angle = ::acos(line.dx() / line.length());
                qreal Pi = atan(1)*4;
                if (line.dy() >= 0)
                    angle = (Pi * 2) - angle;

                QPointF arrowP1 = line.p1() + QPointF(sin(angle + Pi / 3) * arrow_size_,
                                                cos(angle + Pi / 3) * arrow_size_);
                QPointF arrowP2 = line.p1() + QPointF(sin(angle + Pi - Pi / 3) * arrow_size_,
                                                cos(angle + Pi - Pi / 3) * arrow_size_);

                QPolygonF arrowTop;
                arrowTop.clear();
                arrowTop << line.p1() << arrowP1 << arrowP2;

                painter.drawLine(line);
                painter.drawPolygon(arrowTop);///111
                qDebug() << "arrowTop" << arrowTop;
                arrow_top_ = arrowTop;
            }

            }
        else if (PolygonTool == tool_) {
            /* с учётом масштаба */
            QPoint point;
            QPolygon pol = poly.getCoordinates();
            for (int i = 0; i < pol.size(); i++) {
                point.setX(pol.at(i).x());
                point.setY(pol.at(i).y());
                point *= scale_;
                pol.remove(i);
                pol.insert(i, point);
            }
            painter.drawPolygon(pol);
        }
    }

    /* рисуем фигуры */
    drawBoundingBoxes(&painter, &pen);
    drawPolygons(&painter, &pen);
    drawEllipses(&painter, &pen);
    drawArrows(&painter, &pen);
}
Example #4
0
// convert viewport coordinate to the original image (not scaled).
QRect ImageView::viewportToScene(const QRect& rect) {
  // QPolygon poly = mapToScene(imageItem_->rect());
  QPoint topLeft = mapToScene(rect.topLeft()).toPoint();
  QPoint bottomRight = mapToScene(rect.bottomRight()).toPoint();
  return QRect(topLeft, bottomRight);
}
void WindowsModernStyle::drawPrimitive( PrimitiveElement element, const QStyleOption* option,
	QPainter* painter, const QWidget* widget ) const
{
	switch ( element ) {
		case PE_Widget:
			if ( qobject_cast<const QMainWindow*>( widget ) ) {
				QRect rect = option->rect;
				if ( QStatusBar* statusBar = widget->findChild<QStatusBar*>() ) {
					rect.adjust( 0, 0, 0, -statusBar->height() );
					painter->setPen( option->palette.light().color() );
					painter->drawLine( rect.bottomLeft() + QPoint( 0, 1 ),
						rect.bottomRight() + QPoint( 0, 1 ) );
				}
				QLinearGradient gradient( option->rect.topLeft(), option->rect.topRight() );
				gradient.setColorAt( 0.0, m_colorBackgroundBegin );
				gradient.setColorAt( 0.6, m_colorBackgroundEnd );
				painter->fillRect( rect, gradient );
				return;
			}

			if ( qobject_cast<const QToolBox*>( widget ) ) {
				QLinearGradient gradient( option->rect.topLeft(), option->rect.topRight() );
				gradient.setColorAt( 0.4, m_colorBackgroundBegin );
				gradient.setColorAt( 1.0, m_colorBackgroundEnd );
				painter->fillRect( option->rect, gradient );
				return;
			}

			if ( isToolBoxPanel( widget ) ) {
				QLinearGradient gradient( option->rect.topLeft(), option->rect.topRight() );
				gradient.setColorAt( 0.4, m_colorBarMiddle );
				gradient.setColorAt( 1.0, m_colorBarBegin );
				painter->fillRect( option->rect, gradient );
				return;
			}
			break;

		case PE_WindowGradient: {
			QLinearGradient gradient( option->rect.topLeft(), option->rect.topRight() );
			gradient.setColorAt( 0.0, m_colorBackgroundBegin );
			gradient.setColorAt( 0.6, m_colorBackgroundEnd );
			painter->fillRect( option->rect, gradient );
			return;
		}

		case PE_PanelMenuBar:
			return;

		case PE_FrameMenu:
			painter->setPen( m_colorMenuBorder );
			painter->setBrush( Qt::NoBrush );
			painter->drawRect( option->rect.adjusted( 0, 0, -1, -1 ) );

			if ( const QMenu* menu = qobject_cast<const QMenu*>( widget ) ) {
				if ( const QMenuBar* menuBar = qobject_cast<const QMenuBar*>( menu->parent() ) ) {
					QRect rect = menuBar->actionGeometry( menu->menuAction() );
					if ( !rect.isEmpty() ) {
						painter->setPen( m_colorMenuBackground );
						painter->drawLine( 1, 0, rect.width() - 2, 0 );
					}
				}
			}

			if ( const QToolBar* toolBar = qobject_cast<const QToolBar*>( widget ) ) {
				QRect rect = option->rect.adjusted( 1, 1, -1, -1 );
				QLinearGradient gradient;
				if ( toolBar->orientation() == Qt::Vertical )
					gradient = QLinearGradient( rect.topLeft(), rect.topRight() );
				else
					gradient = QLinearGradient( rect.topLeft(), rect.bottomLeft() );
				gradient.setColorAt( 0.0, m_colorBarBegin );
				gradient.setColorAt( 0.4, m_colorBarMiddle );
				gradient.setColorAt( 0.6, m_colorBarMiddle );
				gradient.setColorAt( 1.0, m_colorBarEnd );
				painter->fillRect( rect, gradient );
			}
			return;

		case PE_IndicatorToolBarHandle:
			if ( option->state & State_Horizontal ) {
				for ( int i = option->rect.height() / 5; i <= 4 * ( option->rect.height() / 5 ); i += 5 ) {
					int x = option->rect.left() + 3;
					int y = option->rect.top() + i + 1;
					painter->fillRect( x + 1, y, 2, 2, m_colorHandleLight );
					painter->fillRect( x, y - 1, 2, 2, m_colorHandle );
				}
			} else {
				for ( int i = option->rect.width() / 5; i <= 4 * ( option->rect.width() / 5 ); i += 5 ) {
					int x = option->rect.left() + i + 1;
					int y = option->rect.top() + 3;
					painter->fillRect( x, y + 1, 2, 2, m_colorHandleLight );
					painter->fillRect( x - 1, y, 2, 2, m_colorHandle );
				}
			}
			return;

		case PE_IndicatorToolBarSeparator:
			painter->setPen( m_colorSeparator );
			if ( option->state & State_Horizontal )
				painter->drawLine( ( option->rect.left() + option->rect.right() - 1 ) / 2, option->rect.top() + 2,
					( option->rect.left() + option->rect.right() - 1 ) / 2, option->rect.bottom() - 2 );
			else
				painter->drawLine( option->rect.left() + 2, ( option->rect.top() + option->rect.bottom() - 1 ) / 2,
					option->rect.right() - 2, ( option->rect.top() + option->rect.bottom() - 1 ) / 2 );
			painter->setPen( m_colorSeparatorLight );
			if ( option->state & State_Horizontal )
				painter->drawLine( ( option->rect.left() + option->rect.right() + 1 ) / 2, option->rect.top() + 2,
					( option->rect.left() + option->rect.right() + 1 ) / 2, option->rect.bottom() - 2 );
			else
				painter->drawLine( option->rect.left() + 2, ( option->rect.top() + option->rect.bottom() + 1 ) / 2,
					option->rect.right() - 2, ( option->rect.top() + option->rect.bottom() + 1 ) / 2 );
			return;

		case PE_IndicatorButtonDropDown: {
			QToolBar* toolBar;
			if ( widget && ( toolBar = qobject_cast<QToolBar*>( widget->parentWidget() ) ) ) {
				QRect rect = option->rect.adjusted( -1, 0, -1, -1 );
				bool selected = option->state & State_MouseOver && option->state & State_Enabled;
				bool sunken = option->state & State_Sunken;
				if ( selected || sunken ) {
					painter->setPen( m_colorItemBorder );
					if ( toolBar->orientation() == Qt::Vertical ) {
						if ( sunken )
							painter->setBrush( m_colorItemSunkenEnd );
						else
							painter->setBrush( m_colorItemBackgroundEnd );
					} else {
						QLinearGradient gradient( rect.topLeft(), rect.bottomLeft() );
						if ( sunken ) {
							gradient.setColorAt( 0.0, m_colorItemSunkenBegin );
							gradient.setColorAt( 0.5, m_colorItemSunkenMiddle );
							gradient.setColorAt( 1.0, m_colorItemSunkenEnd );
						} else {
							gradient.setColorAt( 0.0, m_colorItemBackgroundBegin );
							gradient.setColorAt( 0.5, m_colorItemBackgroundMiddle );
							gradient.setColorAt( 1.0, m_colorItemBackgroundEnd );
						}
						painter->setBrush( gradient );
					}
					painter->drawRect( rect );
				}
				QStyleOption optionArrow = *option;
				optionArrow.rect.adjust( 2, 2, -2, -2 );
				drawPrimitive( PE_IndicatorArrowDown, &optionArrow, painter, widget );
				return;
			}
		}

		case PE_IndicatorDockWidgetResizeHandle:
			return;

		case PE_PanelButtonTool:
			if ( widget && widget->inherits( "QDockWidgetTitleButton" ) ) {
				if ( option->state & ( QStyle::State_MouseOver | QStyle::State_Sunken ) ) {
					painter->setPen( m_colorItemBorder );
					painter->setBrush( ( option->state & QStyle::State_Sunken ) ? m_colorItemSunkenMiddle : m_colorItemBackgroundMiddle );
					painter->drawRect( option->rect.adjusted( 0, 0, -1, -1 ) );
				}
				return;
			}
			break;

		case PE_FrameTabWidget:
			if ( isStyledTabWidget( widget ) ) {
				painter->fillRect( option->rect, option->palette.window() );
				return;
			}
			break;

		case PE_FrameTabBarBase:
			if ( isStyledTabBar( widget ) )
				return;
			break;

		default:
			break;
	}

	if ( useVista() )
		QWindowsVistaStyle::drawPrimitive( element, option, painter, widget );
	else
		QWindowsXPStyle::drawPrimitive( element, option, painter, widget );
}
Example #6
0
void ScoreWidget::paintBlankPaper ()
{
  int PaperWidth = m_paperBmp->width();
  int PaperHeight = m_paperBmp->height();
  const int PoolWidth = 60;
  const int Pool2Width = 85;
  const int maxPoolRadius = 20;

  QPainter p(m_paperBmp);
  if (m_landscape)
  {
      p.translate(PaperWidth, 0);
      p.rotate(90);
      qSwap(PaperWidth, PaperHeight);
  }

  p.setRenderHints(QPainter::Antialiasing);
  QRect NewRect = QRect(0, 0, PaperWidth, PaperHeight);
  QImage img(QString(":/pics/scorepaper.png"));
  p.drawImage(0, 0, img);
  p.setPen(Qt::black);

  // Draw borders of paper
  p.drawRect(NewRect);
  QPoint center(PaperWidth/2, PaperHeight-PaperWidth/2);

  // Diagonal lines from bottom corners to circle
  p.drawLine(NewRect.bottomLeft(), center);
  p.drawLine(NewRect.bottomRight(), center);

  // Central vertical line
  p.drawLine( center.x(), 0, center.x(), center.y() );

  // External border of pool
  p.drawRect(PoolWidth, 0, PaperWidth-2*PoolWidth, PaperHeight-PoolWidth);

  // Border of mountain
  p.drawRect(Pool2Width, 0, PaperWidth-2*Pool2Width, PaperHeight-Pool2Width);

  // Player lines
  p.drawLine(0, (PaperHeight-PoolWidth)/2, PoolWidth, (PaperHeight-PoolWidth)/2);
  p.drawLine(PaperWidth, (PaperHeight-PoolWidth)/2, PaperWidth-PoolWidth, (PaperHeight-PoolWidth)/2);
  p.drawLine(PaperWidth/2, PaperHeight, PaperWidth/2, PaperHeight-PoolWidth);

  // Circle with MaxPool value
  QRadialGradient g(center, maxPoolRadius, center+QPoint(-maxPoolRadius/2,-maxPoolRadius/2));
  g.setColorAt(0, Qt::white);
  g.setColorAt(1, qRgb(250, 250, 0));
  
  QBrush b1(g);
  p.setBrush(b1);
  p.drawEllipse(center, maxPoolRadius, maxPoolRadius);

  // Draw text  
  // MaxPool
  QFont fnt(p.font());
  fnt.setBold(true);
  p.setFont(fnt);
  p.drawText(QRect(center.x() - maxPoolRadius, center.y() - maxPoolRadius,
    maxPoolRadius*2, maxPoolRadius*2), QString::number(m_model->optMaxPool), QTextOption(Qt::AlignCenter));
  fnt.setBold(false);
  p.setFont(fnt);
  
  // Players' names
  QBrush brush(qRgb(255, 255, 255));
  p.setBrush(brush);
  const QRect r1 = p.boundingRect(NewRect, Qt::AlignHCenter, m_model->player(1)->nick());
  const QRect r2 = p.boundingRect(NewRect, Qt::AlignHCenter, m_model->player(2)->nick());
  const QRect r3 = p.boundingRect(NewRect, Qt::AlignHCenter, m_model->player(3)->nick());
  p.drawText(QRect(center.x()-r1.width()/2, center.y()+55, r1.width(), r1.height()),
    m_model->player(1)->nick(), QTextOption(Qt::AlignHCenter));
  drawRotatedText(p, center.x() - 30, (PaperHeight - Pool2Width + (m_landscape ? 1 : -1) * r2.width())/2,
    r2.width(), r2.height(), m_landscape ? -90 : 90, m_model->player(2)->nick());
  drawRotatedText(p, center.x() + 30, (PaperHeight - Pool2Width + r3.width())/2,
    r3.width(), r3.height(), -90, m_model->player(3)->nick());

  p.end();
}
Example #7
0
void rosterItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    painter->save();
    painter->setRenderHint(QPainter::TextAntialiasing);
    QVariant value = index.data(Qt::DecorationRole);

    QColor selectedBg(60, 140, 222);
    QColor alternateBg(239, 245, 254);
    QColor selectedText(Qt::white);

    QColor nameTextColor(Qt::black);
    QColor statusTextColor(Qt::darkGray);

    QPixmap pixmap;
    if(value.type() == QVariant::Icon)
    {
        QIcon icon = qvariant_cast<QIcon>(value);
        pixmap = icon.pixmap(QSize(16, 16), QIcon::Normal, QIcon::On);
    }

    QPen penDivision;
//        if(index.row() % 2)
//            painter->fillRect(option.rect, alternateBg);

    if (option.state & QStyle::State_Selected)
    {
        painter->fillRect(option.rect, selectedBg);
//            painter->fillRect(option.rect, option.palette.highlight());
//            penDivision.setColor(option.palette.highlight().color());
        penDivision.setColor(selectedBg);
        nameTextColor = selectedText;
        statusTextColor = selectedText;
    }
    else
    {
        penDivision.setColor(QColor(244, 244, 244));
    }

    QRect rect = option.rect;
    rect.setWidth(pixmap.width());
    rect.setHeight(pixmap.height());
    rect.moveTop(rect.y() + (option.rect.height() - pixmap.height())/2);
    rect.moveLeft(rect.left() + 2);
    painter->drawPixmap(rect, pixmap);

    rect = option.rect;
    rect.setLeft(rect.x() + pixmap.width() + 8);
    rect.moveTop(rect.y() + 3);
    QFont font;
    painter->setFont(font);
    painter->setPen(nameTextColor);
    if(!index.data(Qt::DisplayRole).toString().isEmpty())
        painter->drawText(rect, index.data(Qt::DisplayRole).toString());
    else
        painter->drawText(rect, index.data(rosterItem::BareJid).toString());

    painter->setPen(statusTextColor);
    rect.setTop(rect.y() + rect.height()/2);
    rect.moveTop(rect.y() - 3);
    QString statusText = index.data(rosterItem::StatusText).toString();
    QFontMetrics fontMetrics(font);
    statusText = fontMetrics.elidedText(statusText, Qt::ElideRight, rect.width() - 34);
    painter->drawText(rect, statusText);

    penDivision.setWidth(0);
    painter->setPen(penDivision);

    rect = option.rect;
    QPoint left = rect.bottomLeft();
    left.setX(left.x() + 4);
    QPoint right = rect.bottomRight();
    right.setX(right.x() - 4);
    painter->drawLine(left, right);

    QImage image;
    value = index.data(rosterItem::Avatar);
    if(value.type() == QVariant::Image)
    {
        image = qvariant_cast<QImage>(value);
    }

    pixmap = QPixmap(":/icons/resource/avatar.png");
    rect = option.rect;
    rect.setWidth(pixmap.width());
    rect.setHeight(pixmap.height());
    rect.moveTop(rect.y() + (option.rect.height() - pixmap.height())/2);
    rect.moveLeft(option.rect.x() + option.rect.width() - pixmap.width() - 2);

//    if(image.isNull())
//        painter->drawPixmap(rect, pixmap);
//    else
        painter->drawImage(rect, image);

    painter->restore();
}
Example #8
0
//  When 2 selection intersects, the content of the moving selection is written
//  into the selection that is stationary, at the local intersection rectangle
void CRectangularSelection::drawIntersectionContent(const QPixmap *outsideContent,
   const QRect &world_outsideContentRect,
   const QRect &local_outsideContentRect)
{
   if (0 == outsideContent ||
      !world_outsideContentRect.intersects(rectangularSelection) ||
      !confirmGeometries())
   {
      return;
   }

   QRect intersectionRect = world_outsideContentRect.intersected(rectangularSelection);
   QPoint inter_topLeft = intersectionRect.topLeft();
   QPoint inter_bottomRight = intersectionRect.bottomRight();
   if (inter_topLeft == inter_bottomRight)
   {
      return;
   }

   // determine the local target equivalent to the intersection rectangle
   int target_topLeft_dx = inter_topLeft.x() - rectangularSelection.topLeft().x();
   int target_topLeft_dy = inter_topLeft.y() - rectangularSelection.topLeft().y();
   int target_bottomRight_dx = inter_bottomRight.x() - rectangularSelection.bottomRight().x();
   int target_bottomRight_dy = inter_bottomRight.y() - rectangularSelection.bottomRight().y();
   int target_topLeft_x = local_rectangularSelection.topLeft().x() + target_topLeft_dx;
   int target_topLeft_y = local_rectangularSelection.topLeft().y() + target_topLeft_dy;
   int target_bottomRight_x = local_rectangularSelection.bottomRight().x() + target_bottomRight_dx;
   int target_bottomRight_y = local_rectangularSelection.bottomRight().y() + target_bottomRight_dy;
   QPoint target_ul(target_topLeft_x, target_topLeft_y);
   QPoint target_br(target_bottomRight_x, target_bottomRight_y);
   QRect  target_LocalRect(target_ul, target_br);

   // determine the local source equivalent to the intersection rectangle
   int source_topLeft_dx = inter_topLeft.x() - world_outsideContentRect.topLeft().x();
   int source_topLeft_dy = inter_topLeft.y() - world_outsideContentRect.topLeft().y();
   int source_bottomRight_dx = inter_bottomRight.x() - world_outsideContentRect.bottomRight().x();
   int source_bottomRight_dy = inter_bottomRight.y() - world_outsideContentRect.bottomRight().y();
   int source_topLeft_x = local_outsideContentRect.topLeft().x() + source_topLeft_dx;
   int source_topLeft_y = local_outsideContentRect.topLeft().y() + source_topLeft_dy;
   int source_bottomRight_x = local_outsideContentRect.bottomRight().x() + source_bottomRight_dx;
   int source_bottomRight_y = local_outsideContentRect.bottomRight().y() + source_bottomRight_dy;
   QPoint source_ul(source_topLeft_x, source_topLeft_y);
   QPoint source_br(source_bottomRight_x, source_bottomRight_y);
   QRect  source_LocalRect(source_ul, source_br);

   // draw intersected content to top layer pixmap
   if (0 != topContent)
   {
      delete topContent;
   }
   topContent = new QPixmap(local_contentRect.size());
   topContent->fill(Qt::white);

   QPainter painter(topContent);
   painter.drawPixmap(target_LocalRect, *outsideContent, source_LocalRect);
   painter.end();

   // debugging
   //QRect debugRect0 = outsideContent->rect();
   //debugRect0.adjust(15, 15, 15, 15);
   //emit printSig( target_LocalRect, 
   //              *outsideContent, 
   //               source_LocalRect, 
   //               QString("OUTSIDE CONTENT"));

   QBitmap bmap = topContent->createMaskFromColor(Qt::white, Qt::MaskInColor);
   topContent->setMask(bmap);
}
Example #9
0
  void calculateGeometry()
  {
    // Convert to global points
    QObject* parent__ = parent();
    if ( parent__ == NULL )
      return;
    QWidget* parent_ = static_cast< QWidget* >( parent__ );
    QRect parentRect = parent_ -> geometry();
    parentRect.moveTopLeft( parent_ -> mapToGlobal(QPoint(0,0)) );

    QRect widgetRect( parentRect );
    QLayout* layout_ = layout();
    if ( layout_ != NULL )
    {
      QApplication::instance() -> sendPostedEvents();
      layout_ -> activate();
      layout_ -> update();
    }
    QRect normalGeometry_ = normalGeometry();
    // Use normal geometry if there is any
    if ( normalGeometry_.width() != 0 && normalGeometry_.height() != 0 )
    {
      widgetRect.setWidth( normalGeometry_.width() );
      widgetRect.setHeight( normalGeometry_.height() );
    }
    if ( layout_ != 0 )
    {
      QSize sizeHint = layout_ -> sizeHint();
      if ( widgetRect.height() < sizeHint.height() )
        widgetRect.setHeight( sizeHint.height() );
      if ( widgetRect.width() < sizeHint.width() )
        widgetRect.setWidth( sizeHint.width() );
      widgetRect.setSize( sizeHint );
    }

    QPoint bindTo;

    switch(parentCornerToAnchor_)
    {
      default:
      case Qt::TopLeftCorner:
      bindTo = parentRect.topLeft(); break;
      case Qt::TopRightCorner:
      bindTo = parentRect.topRight(); break;
      case Qt::BottomLeftCorner:
      bindTo = parentRect.bottomLeft(); break;
      case Qt::BottomRightCorner:
      bindTo = parentRect.bottomRight(); break;
    }

    switch(widgetCornerToAnchor_)
    {
      default:
      case Qt::TopLeftCorner:
      widgetRect.moveTopLeft( bindTo ); break;
      case Qt::TopRightCorner:
      widgetRect.moveTopRight( bindTo ); break;
      case Qt::BottomLeftCorner:
      widgetRect.moveBottomLeft( bindTo ); break;
      case Qt::BottomRightCorner:
      widgetRect.moveBottomRight( bindTo ); break;
    }

    QDesktopWidget desktopWidget;
    // If user only has one screen, ensure the popup doesn't go off screen
    // If multiple screens, this could be annoying as the popup can be viewed on a 2nd screen
    if ( desktopWidget.screenCount() == 1)
      widgetRect = desktopWidget.screenGeometry( parent_ ).intersected( widgetRect );
    setGeometry( widgetRect );
  }
Example #10
0
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
void tNavigationPage::paint( QPainter* pPainter, const QStyleOptionGraphicsItem* pOption, QWidget* pWidget )
{
    Q_UNUSED( pOption );
    Q_UNUSED( pWidget );

    //Draw table
    QList<tDataType> displayDataTypes;
    //TODO: need to do FTW
    displayDataTypes << DATA_TYPE_COG << DATA_TYPE_SPEED_SOG << DATA_TYPE_BEARING << DATA_TYPE_DISTANCE_TO_TURN << DATA_TYPE_FUEL_TO_TURN;

    QRect tableRect = AvailableRect();
    //tableRect.setBottom(tableRect.bottom()-50);
    tableRect.setLeft(tableRect.left()+90);
    tableRect.setWidth(161);
    tableRect.setHeight(142);

    pPainter->setPen( QPen( Qt::black, 2.0, Qt::SolidLine, Qt::RoundCap ) );
    
    //draw left and top borders
    pPainter->drawLine(tableRect.topLeft(), tableRect.topRight());
    pPainter->drawLine(tableRect.topLeft(), tableRect.bottomLeft());
    

    static int lineHeight = 28;
    int lineOffset = 0;
    for (QList<tDataType>::iterator dataTypeIter = displayDataTypes.begin(); dataTypeIter != displayDataTypes.end(); ++dataTypeIter)
    {
        //Text
        QString currentLabel = tDigitalData::Caption( *dataTypeIter, true );
        QRect textRect = tableRect;
        textRect.setTop(tableRect.top() + lineOffset);
        textRect.setLeft(tableRect.left() + 1);
        textRect.setHeight(lineHeight);
        textRect.setWidth(52);
        //pPainter->setPen( QPen( QColor(128,128,128) ) );
        //pPainter->setBrush(Qt::red);
        pPainter->fillRect(textRect, QBrush(QColor(187,187,187)));
        pPainter->drawText( textRect, Qt::AlignCenter, currentLabel );

        //Value
        QFont currentFont = pPainter->font();
        currentFont.setBold(true);
        pPainter->setFont(currentFont);
        QRect valueRect = textRect;
        valueRect.setLeft( textRect.left()+textRect.width() );
        valueRect.setWidth(61);

        //TODO: use a timer to only get this when required
        QString valueText("-");
        float navValue;
        bool navValueValid = tDigitalData(tDataId( *dataTypeIter )).ValidValue( navValue );
        if ( navValueValid )
        {
            valueText = QString("%1").arg(navValue);
        }
        

        pPainter->drawText( valueRect, Qt::AlignVCenter | Qt::AlignRight, valueText );
        currentFont.setBold(false);
        pPainter->setFont(currentFont);

        //Units
        if (navValueValid)
        {
            QRect unitsRect = valueRect;
            unitsRect.setLeft( valueRect.left()+valueRect.width() + 5 );
            unitsRect.setWidth(47);
            pPainter->drawText( unitsRect, Qt::AlignVCenter | Qt::AlignLeft, tDigitalData(tDataId( *dataTypeIter )).UnitStr() );
        }

        //Separator
        int rowY = tableRect.y() + lineOffset;
        QLine rowSeparator(tableRect.x(), rowY, tableRect.right(), rowY );
        pPainter->drawLine(rowSeparator);
        lineOffset += lineHeight;

        //Get position data
        tDigitalData position( (tDataId( DATA_TYPE_POSITION )) );

        tRCoord posValue(0,0);
        bool posValid = position.ValidValue( posValue );

        QString latitudeValue("-");
        QString longitudeValue("-");

        //tCoordinate posCoord = tCoordinate( posValue );
        if (posValid)
        {
            //TODO: find out if this logic exists in a common place
            double dblDeg;
            int deg;
            double min;
            char hem;

            dblDeg = RadiansToDegrees( posValue.RLat() );
            hem = dblDeg < 0 ? 'S' : 'N';
            dblDeg = qAbs(dblDeg);
            deg = (int)dblDeg;
            min = 60 * (dblDeg - deg); 

            //latitudeValue = QString("%1:%2'%3").arg(deg).arg(min).arg(hem);
            latitudeValue = QString("%1 %2").arg( posValue.RLat()).arg(hem);

            dblDeg = RadiansToDegrees( posValue.RLon() );
            hem = dblDeg < 0 ? 'W' : 'E';
            dblDeg = qAbs(dblDeg);
            deg = (int)dblDeg;
            min = 60 * (dblDeg - deg); 

            //longitudeValue = QString("%1:%2'%3").arg(deg).arg(min).arg(hem);
            longitudeValue = QString("%1 %2").arg(posValue.RLon()).arg(hem);
        }

        //Lat/Lon display
        QRect latTextRect = AvailableRect();
        latTextRect.setTop(tableRect.bottom()+10);
        latTextRect.setWidth(latTextRect.width()/2);
        latTextRect.setHeight(25);
        pPainter->drawText( latTextRect, Qt::AlignCenter, QString("Latitude").toUpper() ); //TODO: look at translation?
        QRect latValueRect = latTextRect;
        latValueRect.setTop(latTextRect.bottom());
        latValueRect.setLeft(latTextRect.left()+4);
        latValueRect.setWidth(latTextRect.width()-8);
        latValueRect.setHeight(latTextRect.height());
        pPainter->drawRect(latValueRect);
        pPainter->drawText( latValueRect, Qt::AlignCenter, latitudeValue ); //TODO: look at translation?

        QRect lonTextRect = latTextRect;
        lonTextRect.setLeft(latTextRect.right());
        lonTextRect.setTop(latTextRect.top());
        lonTextRect.setWidth(latTextRect.width());
        pPainter->drawText( lonTextRect, Qt::AlignCenter, QString("Longitude").toUpper() ); //TODO: look at translation?
        QRect lonValueRect = lonTextRect;
        lonValueRect.setTop(lonTextRect.bottom());
        lonValueRect.setLeft(lonTextRect.left()+4);
        lonValueRect.setWidth(lonTextRect.width()-8);
        lonValueRect.setHeight(lonTextRect.height());
        pPainter->drawRect(lonValueRect);
        pPainter->drawText( lonValueRect, Qt::AlignCenter, longitudeValue ); //TODO: look at translation?
    }

    //draw bottom border
    pPainter->drawLine(tableRect.bottomLeft(), tableRect.bottomRight());
}
Example #11
0
bool RectPicker::end(bool ok)
{
	
	if (!ok)//更改代码处:,正常结束后,并不停止。只有reset时候,end(false)停止选择,重置状态机
		QwtPicker::end(ok);
	if (!ok)
		return false;

	QwtPlot *plot = QwtPlotPicker::plot();
	if (!plot)
		return false;

	const QPolygon points = selection();
	if (points.count() == 0)
		return false;

	QwtPickerMachine::SelectionType selectionType =
		QwtPickerMachine::NoSelection;

	if (stateMachine())
		selectionType = stateMachine()->selectionType();

	switch (selectionType)
	{
	case QwtPickerMachine::PointSelection:
	{
												const QPointF pos = invTransform(points.first());
												Q_EMIT selected(pos);
												break;
	}
	case QwtPickerMachine::RectSelection:
	{
											if (points.count() >= 2)
											{
												const QPoint p1 = points.first();
												const QPoint p2 = points.last();
												QPointF pF1 = invTransform(p1);
												QPointF pF2 = invTransform(p2);
												const QRect rect = QRect(p1, p2).normalized();
												const QRect rect11 = QRect(p1, p2);
												QPoint pp1 = rect.topLeft();
												QPoint pp2 = rect.bottomRight();
												//const QRect rect = QRect(p1, p2);
												QRectF rect1 = invTransform(rect);
												QPointF topLeft = rect1.topLeft();
												QPointF bottomRight = rect1.bottomRight();
												Q_EMIT selected(invTransform(rect));
											}
											break;
	}
	case QwtPickerMachine::PolygonSelection:
	{
												QVector<QPointF> dpa(points.count());
												for (int i = 0; i < points.count(); i++)
													dpa[i] = invTransform(points[i]);

												Q_EMIT selected(dpa);
	}
	default:
		break;
	}
	return ok;
}
Example #12
0
void
MpcToolbarStyle::drawControl(ControlElement control, const QStyleOption *option,
                      QPainter *painter, const QWidget *widget) const
{
    if(control == CE_ToolBar)
    {
        if (const QStyleOptionToolBar *toolbar = qstyleoption_cast<const QStyleOptionToolBar *>(option)) {
            QRect rect = option->rect;

            if( toolbar->toolBarArea == Qt::BottomToolBarArea &&
                toolbar->positionOfLine == QStyleOptionToolBar::End )
            {
                painter->setPen(QPen(option->palette.light().color()));
                painter->drawLine(rect.topLeft().x(),
                            rect.topLeft().y(),
                            rect.topRight().x(),
                            rect.topRight().y());

                painter->setPen(QPen(option->palette.light().color()));
                painter->drawLine(rect.topLeft().x(),
                            rect.topLeft().y(),
                            rect.bottomLeft().x(),
                            rect.bottomLeft().y());

                painter->setPen(QPen(option->palette.dark().color()));
                painter->drawLine(rect.topRight().x(),
                            rect.topRight().y(),
                            rect.bottomRight().x(),
                            rect.bottomRight().y());

            }
            else if( toolbar->toolBarArea == Qt::BottomToolBarArea &&
                toolbar->positionOfLine == QStyleOptionToolBar::Beginning )
            {
                painter->setPen(QPen(option->palette.light().color()));
                painter->drawLine(rect.topLeft().x(),
                            rect.topLeft().y(),
                            rect.bottomLeft().x(),
                            rect.bottomLeft().y());

                painter->setPen(QPen(option->palette.dark().color()));
                painter->drawLine(rect.topRight().x(),
                            rect.topRight().y(),
                            rect.bottomRight().x(),
                            rect.bottomRight().y());

                painter->setPen(QPen(option->palette.dark().color()));
                painter->drawLine(rect.bottomLeft().x(),
                            rect.bottomLeft().y(),
                            rect.bottomRight().x(),
                            rect.bottomRight().y());
            }
            else
            {
                QWindowsStyle::drawControl(control,toolbar, painter, widget);
            }
        }
    }
    else
    {
        QWindowsStyle::drawControl(control,option, painter, widget);
    }
}
Example #13
0
void DisplayWidget::mouseReleaseEvent(QMouseEvent *event)
{
    QVariant v;
    v.setValue(selectedTile);

    switch(currentTool)
    {
    case t_pen:
    {
        model()->setData(this->indexAt(event->pos()), v);
        break;
    }
    case t_box:
    case t_hollow_box:
    case t_circle:
    case t_hollow_circle:
    {
        rubberBand->hide();

        int headerHeight = this->horizontalHeader()->height();
        int headerWidth = this->verticalHeader()->width();

        // rubber band draws based on the displays 0,0 as origin
        // indexes use inside corner of the headers as 0,0
        //
        // v-- this is 0,0 for rubber band
        // []=================
        // ||+<-- this is 0,0 for table fields
        // ||
        QRect selection = rubberBand->geometry().adjusted(-headerWidth, -headerHeight, -headerWidth, -headerHeight);
        QModelIndex center = this->indexAt(selection.center());
        QModelIndex topLeft = this->indexAt(selection.topLeft());
        QModelIndex bottomRight = this->indexAt(selection.bottomRight());

        // determine selections
        if(currentTool == t_box)
        {
            for(int i = topLeft.column(); i <= bottomRight.column(); i++)
            {
                for(int j = topLeft.row(); j <= bottomRight.row(); j++)
                {
                    model()->setData(model()->index(j, i), v);
                }
            }
        }
        else if(currentTool == t_hollow_box)
        {
            for(int i = topLeft.column(); i <= bottomRight.column(); i++)
            {
                model()->setData(model()->index(topLeft.row(), i), v);
                model()->setData(model()->index(bottomRight.row(), i), v);
            }
            for(int i = topLeft.row(); i <= bottomRight.row(); i++)
            {
                model()->setData(model()->index(i, topLeft.column()), v);
                model()->setData(model()->index(i, bottomRight.column()), v);
            }
        }
        // currently suffer w/even diameters, index at center does not necessarily correlate to
        // center of the actual circle.  adjust to use diameter / 2 for calculations.
        else if(currentTool == t_circle)
        {
            // x-radius
            double a = bottomRight.column() - center.column();
            // y-radius
            double b = topLeft.row() - center.row();

            // (x-h)^2/a^2 + (y-k)^2/b^2 <= 1
            for(int i = topLeft.column(); i <= bottomRight.column(); i++)
            {
                for(int j = topLeft.row(); j <= bottomRight.row(); j++)
                {
                    double topx = i - center.column();
                    double topy = j - center.row();
                    if(
                      (((topx * topx) / (a * a)) + ((topy * topy) / (b * b))) <= 1.0
                      )
                    {
                        model()->setData(model()->index(j, i), v);
                    }
                }
            }

        }
        else if(currentTool == t_hollow_circle)
        {
            // x(t) = (right - center) * cos(t) = a * cos(t)
            // y(t) = (top - center) * sin(t) = b * sin(t)
            int a = bottomRight.column() - center.column();
            int b = topLeft.row() - center.row();

            for(double d = 0.0; d <= 2 * M_PI; d+=(M_PI / 100))
            {
                int x = center.column() + qRound(a * cos(d));
                int y = center.row() + qRound(b * sin(d));
                model()->setData(model()->index(y, x), v);
            }
        }
        break;
    }
    default:
        break;
    }
}
Example #14
0
void QToolButtonPrivate::popupTimerDone()
{
    Q_Q(QToolButton);
    popupTimer.stop();
    if (!menuButtonDown && !down)
        return;

    menuButtonDown = true;
    QPointer<QMenu> actualMenu;
    bool mustDeleteActualMenu = false;
    if(menuAction) {
        actualMenu = menuAction->menu();
    } else if (defaultAction && defaultAction->menu()) {
        actualMenu = defaultAction->menu();
    } else {
        actualMenu = new QMenu(q);
        mustDeleteActualMenu = true;
        for(int i = 0; i < actions.size(); i++)
            actualMenu->addAction(actions.at(i));
    }
    repeat = q->autoRepeat();
    q->setAutoRepeat(false);
    bool horizontal = true;
#if !defined(QT_NO_TOOLBAR)
    QToolBar *tb = qobject_cast<QToolBar*>(parent);
    if (tb && tb->orientation() == Qt::Vertical)
        horizontal = false;
#endif
    QPoint p;
    QRect screen = QApplication::desktop()->availableGeometry(q);
    QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint();
    QRect rect = q->rect();
    if (horizontal) {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomRight());
            } else {
                p = q->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
            }
            p.rx() -= sh.width();
        } else {
            if (q->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
                p = q->mapToGlobal(rect.bottomLeft());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
            }
        }
    } else {
        if (q->isRightToLeft()) {
            if (q->mapToGlobal(QPoint(rect.left(), 0)).x() - sh.width() <= screen.x()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft());
                p.rx() -= sh.width();
            }
        } else {
            if (q->mapToGlobal(QPoint(rect.right(), 0)).x() + sh.width() <= screen.right()) {
                p = q->mapToGlobal(rect.topRight());
            } else {
                p = q->mapToGlobal(rect.topLeft() - QPoint(sh.width(), 0));
            }
        }
    }
    p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
    p.ry() += 1;
    QPointer<QToolButton> that = q;
    actualMenu->setNoReplayFor(q);
    if (!mustDeleteActualMenu) //only if action are not in this widget
        QObject::connect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));
    QObject::connect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    actualMenu->d_func()->causedPopup.widget = q;
    actualMenu->d_func()->causedPopup.action = defaultAction;
    actionsCopy = q->actions(); //(the list of action may be modified in slots)
    actualMenu->exec(p);
    QObject::disconnect(actualMenu, SIGNAL(aboutToHide()), q, SLOT(_q_updateButtonDown()));
    if (mustDeleteActualMenu)
        delete actualMenu;
    else
        QObject::disconnect(actualMenu, SIGNAL(triggered(QAction*)), q, SLOT(_q_menuTriggered(QAction*)));

    if (!that)
        return;

    actionsCopy.clear();

    if (repeat)
        q->setAutoRepeat(true);
}
Example #15
0
void FancyTabBar::paintTab(QPainter* painter, int tabIndex) const
{
    if (!validIndex(tabIndex)) {
        qWarning("invalid index");
        return;
    }
    painter->save();

    QRect rect = tabRect(tabIndex);
    bool selected = (tabIndex == m_currentIndex);

    if (selected) {
        //background
        painter->save();
        QLinearGradient grad(rect.topLeft(), rect.topRight());
        grad.setColorAt(0, QColor(255, 255, 255, 140));
        grad.setColorAt(1, QColor(255, 255, 255, 210));
        painter->fillRect(rect.adjusted(0, 0, 0, -1), grad);
        painter->restore();

        //shadows
        painter->setPen(QColor(0, 0, 0, 110));
        painter->drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1));
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
        painter->setPen(QColor(0, 0, 0, 40));
        painter->drawLine(rect.topLeft(), rect.bottomLeft());

        //highlights
        painter->setPen(QColor(255, 255, 255, 50));
        painter->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2));
        painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1));
        painter->setPen(QColor(255, 255, 255, 40));
        painter->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
        painter->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
        painter->drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1));
    }

    QString tabText(painter->fontMetrics().elidedText(this->tabText(tabIndex), Qt::ElideMiddle, width()));
    QRect tabTextRect(tabRect(tabIndex));
    QRect tabIconRect(tabTextRect);
    tabIconRect.adjust(+4, +4, -4, -4);
    tabTextRect.translate(0, -2);
    QFont boldFont(painter->font());
    boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
    boldFont.setBold(true);
    painter->setFont(boldFont);
    painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
    int textFlags = Qt::AlignCenter | Qt::AlignBottom;
    painter->drawText(tabTextRect, textFlags, tabText);
    painter->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
#ifndef Q_OS_MACOS
    if (!selected) {
        painter->save();
        int fader = int(m_tabs[tabIndex]->fader());
        QLinearGradient grad(rect.topLeft(), rect.topRight());
        grad.setColorAt(0, Qt::transparent);
        grad.setColorAt(0.5, QColor(255, 255, 255, fader));
        grad.setColorAt(1, Qt::transparent);
//        painter->fillRect(rect, grad);
//        painter->setPen(QPen(grad, 1.0));
        painter->fillRect(rect, QColor(255, 255, 255, fader));
        painter->setPen(QPen(QColor(255, 255, 255, fader), 1.0));
        painter->drawLine(rect.topLeft(), rect.topRight());
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
        painter->restore();
    }
#endif

    const int textHeight = painter->fontMetrics().height();
    tabIconRect.adjust(0, 4, 0, -textHeight);
    Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, selected ? QIcon::Selected : QIcon::Normal);

    painter->translate(0, -1);
    painter->drawText(tabTextRect, textFlags, tabText);
    painter->restore();
}
Example #16
0
void CWizNoteStyle::drawMultiLineListWidgetItem(const QStyleOptionViewItemV4 *vopt, QPainter *p, const CWizMultiLineListWidget *view) const
{
    bool imageAlignLeft = view->imageAlignLeft();
    int imageWidth = view->imageWidth();
    int lineCount = view->lineCount();
    int wrapTextLineText = view->wrapTextLineIndex();
    const QPixmap img = view->itemImage(vopt->index);

    p->save();
    p->setClipRect(vopt->rect);

    QRect textLine = vopt->rect;
    textLine.adjust(4, 0, -4, 0);
    p->setPen(Utils::StyleHelper::listViewItemSeperator());
    p->drawLine(textLine.bottomLeft(), textLine.bottomRight());

    QRect textRect = vopt->rect;
    //QRect textRect = subElementRect(SE_ItemViewItemText, vopt, view);

    // draw the background
    drawMultiLineItemBackground(vopt, p, view);

    if (!img.isNull() && img.width() > 0 && img.height() > 0)
    {
        QRect imageRect = textRect;
        if (imageAlignLeft)
        {
            imageRect.setRight(imageRect.left() + imageWidth + 16);
            imageRect.adjust(4, 4, -4, -4);
            textRect.setLeft(imageRect.right());
        }
        else
        {
            imageRect.setLeft(imageRect.right() - imageWidth + 16);
            imageRect.adjust(4, 4, -4, -4);
            textRect.setRight(imageRect.left());
        }

        if (img.width() > imageRect.width() || img.height() > imageRect.height())
        {
            double fRate = std::min<double>(double(imageRect.width()) / img.width(), double(imageRect.height()) / img.height());
            int newWidth = int(img.width() * fRate);
            int newHeight = int(img.height() * fRate);
            //
            int adjustX = (imageRect.width() - newWidth) / 2;
            int adjustY = (imageRect.height() - newHeight) / 2;
            imageRect.adjust(adjustX, adjustY, -adjustX, -adjustY);
        }
        else
        {
            int adjustX = (imageRect.width() - img.width()) / 2;
            int adjustY = (imageRect.height() - img.height()) / 2;
            imageRect.adjust(adjustX, adjustY, -adjustX, -adjustY);
        }
        p->drawPixmap(imageRect, img);
    }

    // draw the text
    QPalette::ColorGroup cg = vopt->state & QStyle::State_Enabled
                              ? QPalette::Normal : QPalette::Disabled;
    if (cg == QPalette::Normal && !(vopt->state & QStyle::State_Active))
        cg = QPalette::Inactive;

    if (vopt->state & QStyle::State_Selected) {
        p->setPen(vopt->palette.color(cg, QPalette::HighlightedText));
    } else {
        p->setPen(vopt->palette.color(cg, QPalette::Text));
    }
    if (vopt->state & QStyle::State_Editing) {
        p->setPen(vopt->palette.color(cg, QPalette::Text));
        p->drawRect(textRect.adjusted(0, 0, -1, -1));
    }

    textRect.adjust(8, 8, -8, -8);
    bool selected = vopt->state.testFlag(State_Selected);
    int lineHeight = vopt->fontMetrics.height() + 2;

    for (int line = 0; line < wrapTextLineText && line < lineCount; line++)
    {
        QColor color = (0 == line) ? Utils::StyleHelper::listViewMultiLineFirstLine(selected)
            : Utils::StyleHelper::listViewMultiLineOtherLine(selected);
        //
        CString strText = view->itemText(vopt->index, line);
        color = view->itemTextColor(vopt->index, line, selected, color);
        QRect rc = textRect;
        rc.setTop(rc.top() + line * lineHeight);
        rc.setHeight(lineHeight);
        ::WizDrawTextSingleLine(p, rc, strText,  Qt::TextSingleLine | Qt::AlignVCenter, color, true);
    }

    int line = wrapTextLineText;
    if (line < lineCount)
    {
        CString strText = view->itemText(vopt->index, line);
        for (; line < lineCount; line++)
        {
            QColor color = Utils::StyleHelper::listViewMultiLineOtherLine(selected);
            //
            color = view->itemTextColor(vopt->index, line, selected, color);
            QRect rc = textRect;
            rc.setTop(rc.top() + line * lineHeight);
            rc.setHeight(lineHeight);
            bool elidedText = (line == lineCount - 1);
            ::WizDrawTextSingleLine(p, rc, strText,  Qt::TextSingleLine | Qt::AlignVCenter, color, elidedText);
        }
    }

    // draw the focus rect
    if (vopt->state & QStyle::State_HasFocus) {
        QStyleOptionFocusRect o;
        o.QStyleOption::operator=(*vopt);
        o.rect = subElementRect(SE_ItemViewItemFocusRect, vopt, view);
        o.state |= QStyle::State_KeyboardFocusChange;
        o.state |= QStyle::State_Item;
        QPalette::ColorGroup cg = (vopt->state & QStyle::State_Enabled)
                                  ? QPalette::Normal : QPalette::Disabled;
        o.backgroundColor = vopt->palette.color(cg, (vopt->state & QStyle::State_Selected)
                                                ? QPalette::Highlight : QPalette::Window);
        proxy()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, p, view);
    }

    //draw extra image
    QRect rcExtra;
    QPixmap pixExtra;
    if (view->itemExtraImage(vopt->index, vopt->rect, rcExtra, pixExtra))
    {
        p->drawPixmap(rcExtra, pixExtra);
    }

    p->restore();
}
Example #17
0
void FancyTabProxyStyle::drawControl(
    ControlElement element, const QStyleOption* option,
    QPainter* p, const QWidget* widget) const
{

    const QStyleOptionTab* v_opt = qstyleoption_cast<const QStyleOptionTab*>(option);

    if (element != CE_TabBarTab || !v_opt) {
        QProxyStyle::drawControl(element, option, p, widget);
        return;
    }

    const QRect rect = v_opt->rect;
    const bool selected = v_opt->state & State_Selected;
    const bool vertical_tabs = v_opt->shape == QTabBar::RoundedWest;
    const QString text = v_opt->text;

    if (selected) {
        //background
        p->save();
        QLinearGradient grad(rect.topLeft(), rect.topRight());
        grad.setColorAt(0, QColor(255, 255, 255, 140));
        grad.setColorAt(1, QColor(255, 255, 255, 210));
        p->fillRect(rect.adjusted(0, 0, 0, -1), grad);
        p->restore();

        //shadows
        p->setPen(QColor(0, 0, 0, 110));
        p->drawLine(rect.topLeft() + QPoint(1, -1), rect.topRight() - QPoint(0, 1));
        p->drawLine(rect.bottomLeft(), rect.bottomRight());
        p->setPen(QColor(0, 0, 0, 40));
        p->drawLine(rect.topLeft(), rect.bottomLeft());

        //highlights
        p->setPen(QColor(255, 255, 255, 50));
        p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0, 2));
        p->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0, 1));
        p->setPen(QColor(255, 255, 255, 40));
        p->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
        p->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
        p->drawLine(rect.bottomLeft() + QPoint(0, -1), rect.bottomRight() - QPoint(0, 1));
    }

    QTransform m;
    if (vertical_tabs) {
        m = QTransform::fromTranslate(rect.left(), rect.bottom());
        m.rotate(-90);
    }
    else {
        m = QTransform::fromTranslate(rect.left(), rect.top());
    }

    const QRect draw_rect(QPoint(0, 0), m.mapRect(rect).size());

    p->save();
    p->setTransform(m);

    QRect icon_rect(QPoint(8, 0), v_opt->iconSize);
    QRect text_rect(icon_rect.topRight() + QPoint(4, 0), draw_rect.size());
    text_rect.setRight(draw_rect.width());
    icon_rect.translate(0, (draw_rect.height() - icon_rect.height()) / 2);

    QFont boldFont(p->font());
    boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
    boldFont.setBold(true);
    p->setFont(boldFont);
    p->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
    int textFlags = Qt::AlignHCenter | Qt::AlignVCenter;
    p->drawText(text_rect, textFlags, text);
    p->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
    if (widget) {
        const QString fader_key = "tab_" + text + "_fader";
        const QString animation_key = "tab_" + text + "_animation";

        const QString tab_hover = widget->property("tab_hover").toString();
        int fader = widget->property(fader_key.toUtf8().constData()).toInt();
        QPropertyAnimation* animation = widget->property(animation_key.toUtf8().constData()).value<QPropertyAnimation*>();

        if (!animation) {
            QWidget* mut_widget = const_cast<QWidget*>(widget);
            fader = 0;
            mut_widget->setProperty(fader_key.toUtf8().constData(), fader);
            animation = new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget);
            connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update()));
            mut_widget->setProperty(animation_key.toUtf8().constData(), QVariant::fromValue(animation));
        }

        if (text == tab_hover) {
            if (animation->state() != QAbstractAnimation::Running && fader != 40) {
                animation->stop();
                animation->setDuration(80);
                animation->setEndValue(40);
                animation->start();
            }
        }
        else {
            if (animation->state() != QAbstractAnimation::Running && fader != 0) {
                animation->stop();
                animation->setDuration(160);
                animation->setEndValue(0);
                animation->start();
            }
        }

        if (!selected) {
            p->save();
            p->fillRect(draw_rect, QColor(255, 255, 255, fader));
            p->setPen(QPen(QColor(255, 255, 255, fader), 1.0));
            p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
            p->drawLine(draw_rect.bottomRight(), vertical_tabs ? draw_rect.topRight() : draw_rect.bottomLeft());
            p->restore();
        }
    }

    Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, selected ? QIcon::Selected : QIcon::Normal);

    p->drawText(text_rect.translated(0, -1), textFlags, text);

    p->restore();
}
Example #18
0
void CDraw2D::drawRelease(const QPoint &p)
{
   switch (CDrawSettings_2D::getInstance()->getShape())
   {
   case(SNoShape) :
   {
      emit activateMouseMovement(false);
      //activeMouse = false;
      noShapePolygon << p;
      //if(releasePoint == _last)
      //{
      //   drawPoint(tmpClr, releasePoint);
      //}
      C2DPixmapSegment *segment = createSubpixmapFromPolygon(noShapePolygon, TO_LINES);
      emit appendPixmapSegment(segment);
      polyLine = noShapePolygon;
      //drawPolyLine();
      polyLine.clear();
      blankAidBuffer();
      break;
   }
   case(SLine) :
   {
      emit activateMouseMovement(false);
      //activeMouse = false;
      aidOn = false;
      blankAidBuffer();
      QPolygon linePoly;
      linePoly << _last << p;
      emit appendPixmapSegment(createSubpixmapFromPolygon(linePoly, TO_LINES));
      //drawLine(p);
      break;
   }
   case(SRectangle) :
   {
      emit activateMouseMovement(false);
      //activeMouse = false;
      aidOn = false;
      blankAidBuffer();
      QPolygon rectPoly;
      QRect drawRect;
      drawRect.setTopLeft(_last);
      drawRect.setBottomRight(p);
      rectPoly << drawRect.topLeft()
         << drawRect.topRight()
         << drawRect.bottomRight()
         << drawRect.bottomLeft()
         << drawRect.topLeft();

      emit appendPixmapSegment(createSubpixmapFromPolygon(rectPoly, TO_RECT)); // draw the polygon out as a rectangle
      //drawRectangle(p);
      break;
   }
   case(SRoundedRectangle) :
   {
      emit activateMouseMovement(false);
      //activeMouse = false;
      aidOn = false;
      blankAidBuffer();
      QPolygon rectPoly;
      QRect drawRect;
      drawRect.setTopLeft(_last);
      drawRect.setBottomRight(p);
      rectPoly << drawRect.topLeft()
         << drawRect.topRight()
         << drawRect.bottomRight()
         << drawRect.bottomLeft()
         << drawRect.topLeft();

      emit appendPixmapSegment(createSubpixmapFromPolygon(rectPoly, TO_ROUNDED_RECT));
      //drawRoundedRectangle(p);
      break;
   }
   case(SEllipse) :
   {
      emit activateMouseMovement(false);
      //activeMouse = false;
      aidOn = false;
      blankAidBuffer();
      QPolygon ellipsePoly;
      ellipsePoly << _last << p;
      emit appendPixmapSegment(createSubpixmapFromPolygon(ellipsePoly, TO_ELLIPSE));
      //drawEllipse(p);
      break;
   }
   case(SArc) :
   {
      if (radius == 0)
      {
         Quadrant quadr;
         radius = calcVectorLength(origo, p);
         alphaDegrees = calcAngleBetweenLines(origo, p, &quadr);
         alphaQuadrant = quadr;
         lastQuadrant = quadr;
         topLeftForCircular = QPoint(origo.x() - radius, origo.y() - radius);
         bottomRightForCircular = QPoint(origo.x() + radius, origo.y() + radius);

         emit activateMouseMovement(true);
         //activeMouse = true;
      }
      else
      {
         emit activateMouseMovement(false);
         //activeMouse = false;
         blankAidBuffer();
         QPolygon arcPoly;
         arcPoly << topLeftForCircular << bottomRightForCircular;
         emit appendPixmapSegment(createSubpixmapFromPolygon(arcPoly, TO_ARC));
         //drawArc();
         radius = 0;
         clockCount = 0;
         aidOn = false;
      }
      break;
   }
   case(SPie) :
   {
      if (radius == 0)
      {
         Quadrant quadr;
         radius = calcVectorLength(origo, p);
         alphaDegrees = calcAngleBetweenLines(origo, p, &quadr);
         alphaQuadrant = quadr;
         lastQuadrant = quadr;
         topLeftForCircular = QPoint(origo.x() - radius, origo.y() - radius);
         bottomRightForCircular = QPoint(origo.x() + radius, origo.y() + radius);

         emit activateMouseMovement(true);
         //activeMouse = true;
      }
      else
      {
         emit activateMouseMovement(false);
         //activeMouse = false;
         blankAidBuffer();
         QPolygon piePoly;
         piePoly << topLeftForCircular << bottomRightForCircular;
         emit appendPixmapSegment(createSubpixmapFromPolygon(piePoly, TO_PIE));
         //drawPie();
         radius = 0;
         clockCount = 0;
         aidOn = false;
      }
      break;
   }
   case(SChord) :
   {
      if (radius == 0)
      {
         Quadrant quadr;
         radius = calcVectorLength(origo, p);
         alphaDegrees = calcAngleBetweenLines(origo, p, &quadr);
         alphaQuadrant = quadr;
         lastQuadrant = quadr;
         topLeftForCircular = QPoint(origo.x() - radius, origo.y() - radius);
         bottomRightForCircular = QPoint(origo.x() + radius, origo.y() + radius);
         emit activateMouseMovement(true);
         //activeMouse = true;
      }
      else
      {
         emit activateMouseMovement(false);
         //activeMouse = false;
         blankAidBuffer();
         QPolygon chordPoly;
         chordPoly << topLeftForCircular << bottomRightForCircular;
         emit appendPixmapSegment(createSubpixmapFromPolygon(chordPoly, TO_CHORD));
         //drawChord();
         clockCount = 0;
         radius = 0;
         aidOn = false;
      }
      break;
   }
   case(SPolyline) :
   {
      break;
   }
   case(SPolygon) :
   {
      break;
   }
   default:
   {
      break;
   }
   }

   // remember the current mouse position
   _last = p;
   if (m_first)
   {
      emit adjustCanvas();
      m_first = false;
   }
}
Example #19
0
FaceItem::FaceItem(QGraphicsItem* const parent, QGraphicsScene* const scene, const QRect& rect,
                   double scale, const QString& name, double originalscale)
        : QGraphicsObject(parent), d(new Private)
{
    setAcceptHoverEvents(true);

    d->origScale     = originalscale;
    d->scale         = scale;
    d->origRect      = rect;
    d->sceneWidth    = scene->width();
    d->sceneHeight   = scene->height();

    // Scale all coordinates to fit the initial size of the scene
    d->x1 = rect.topLeft().x()     * scale;
    d->y1 = rect.topLeft().y()     * scale;
    d->x2 = rect.bottomRight().x() * scale;
    d->y2 = rect.bottomRight().y() * scale;

    // A QRect containing coordinates for the face rectangle
    QRect scaledRect;
    scaledRect.setTopLeft(QPoint(d->x1, d->y1));
    scaledRect.setBottomRight(QPoint(d->x2, d->y2));

    // marquee
    FancyRect* const fancy = new FancyRect(scaledRect);
    d->faceMarquee         = new Marquee(fancy);
    scene->addItem(d->faceMarquee);

    // Make a new QGraphicsTextItem for writing the name text, and a new QGraphicsRectItem to draw a good-looking, semi-transparent bounding box.
    d->nameRect = new QGraphicsRectItem(0);
    scene->addItem(d->nameRect);

    d->faceName = new QGraphicsTextItem(name, 0);
    scene->addItem(d->faceName);

    // Make the bounding box for the name update itself to cover all the text whenever contents are changed
    QTextDocument* const doc = d->faceName->document();
    QTextOption o;
    o.setAlignment(Qt::AlignCenter);
    doc->setDefaultTextOption(o);

    // Get coordinates of the name relative the the scene
    QRectF r = d->faceName->mapRectToScene(d->faceName->boundingRect());

    // Draw the bounding name rectangle with the scene coordinates
    d->nameRect->setRect(r);
    QPen p(QColor(QString::fromLatin1("white")));
    p.setWidth(3);
    d->nameRect->setPen(p);
    d->nameRect->setBrush(QBrush(QColor(QString::fromLatin1("black"))));
    d->nameRect->setOpacity(0.6);
    d->nameRect->show();

    // Draw the name input item
    d->faceName->setDefaultTextColor(QColor(QString::fromLatin1("white")));
    d->faceName->setFont(QFont(QString::fromLatin1("Helvetica"), 9));
    d->faceName->setTextInteractionFlags(Qt::TextEditorInteraction);
    d->faceName->setOpacity(1);

    //---------------------

    QPixmap rejectPix  = QIcon::fromTheme(QString::fromLatin1("window-close")).pixmap(16, 16);
    d->rejectButton    = new Button( rejectPix, rejectPix);
    scene->addItem(d->rejectButton);
    d->rejectButton->show();

    QPixmap acceptPix  = QIcon::fromTheme(QString::fromLatin1("dialog-ok-apply")).pixmap(16, 16);
    d->acceptButton    = new Button( acceptPix, acceptPix);
    scene->addItem(d->acceptButton);
    //d->acceptButton->show();

    d->suggestionRejectButton = new Button(rejectPix, rejectPix);
    scene->addItem(d->suggestionRejectButton);
    //d->suggestionAcceptButton->hide();

    d->suggestionAcceptButton = new Button(acceptPix, acceptPix);
    scene->addItem(d->suggestionAcceptButton);
    //d->suggestionRejectButton->hide();

    update();

    switchToEditMode();

    d->acceptButton->hide();

    connect(d->rejectButton, &Button::clicked, this, &FaceItem::reject);

    connect(d->acceptButton, &Button::clicked, this, &FaceItem::accepted);

    connect(d->suggestionAcceptButton, &Button::clicked, this, &FaceItem::slotSuggestionAccepted);

    connect(d->suggestionRejectButton, &Button::clicked, this, &FaceItem::slotSuggestionRejected);

    connect(doc, SIGNAL(contentsChanged()),
            this, SLOT(update()));

    connect(d->faceMarquee, &Marquee::changed, this, &FaceItem::update);
}
Example #20
0
void Selection::paint(QPainter &painter, qreal zoom, QRectF region __attribute__((unused)))
{
  QTransform scaleTrans;
  scaleTrans = scaleTrans.scale(zoom, zoom);

  QTransform paintTrans;
  paintTrans.translate(m_selectionPolygon.boundingRect().center().x() * zoom, m_selectionPolygon.boundingRect().center().y() * zoom);
  paintTrans.rotate(m_angle);
  paintTrans.translate(-m_selectionPolygon.boundingRect().center().x() * zoom, -m_selectionPolygon.boundingRect().center().y() * zoom);

  painter.setTransform(paintTrans, true);

  painter.setRenderHint(QPainter::Antialiasing, true);
  painter.drawImage(scaleTrans.map(m_selectionPolygon).boundingRect(), m_buffer, QRectF(m_buffer.rect()));

  QPen pen;
  //  pen.setStyle(Qt::DashLine);
  pen.setStyle(Qt::SolidLine);
  pen.setWidth(2);
  pen.setCapStyle(Qt::RoundCap);
  //  pen.setColor(QColor(0, 180, 0, 255));
  painter.setBrush(QBrush(QColor(127, 127, 127, 50), Qt::SolidPattern));
  //  painter.setBrush(QBrush(QColor(255, 165, 0, 50), Qt::SolidPattern));
  //  painter.setBrush(QBrush(QColor(0, 255, 0, 50), Qt::SolidPattern));
  painter.setPen(pen);
  if (!m_finalized)
  {
    painter.drawPolygon(scaleTrans.map(m_selectionPolygon), Qt::OddEvenFill);
  }
  else
  {

    // draw GrabZones for resizing
    pen.setColor(QColor(127, 127, 127, 255));
    //    pen.setColor(QColor(255,255,255,255));
    pen.setWidthF(0.5);
    painter.setPen(pen);
    QRect brect = scaleTrans.map(m_selectionPolygon).boundingRect().toRect();
    qreal ad = m_ad;
    painter.drawLine(brect.topLeft() - QPointF(0, ad), brect.bottomLeft() + QPointF(0, ad));
    painter.drawLine(brect.topRight() - QPointF(0, ad), brect.bottomRight() + QPointF(0, ad));
    painter.drawLine(brect.topLeft() - QPointF(ad, 0), brect.topRight() + QPointF(ad, 0));
    painter.drawLine(brect.bottomLeft() - QPointF(ad, 0), brect.bottomRight() + QPointF(ad, 0));

    pen.setWidth(2);
    //    pen.setColor(QColor(0,0,0,127));
    painter.setPen(pen);
    QRectF outerRect = scaleTrans.map(m_selectionPolygon).boundingRect().adjusted(-m_ad, -m_ad, m_ad, m_ad);
    // draw bounding rect
    painter.drawRect(outerRect);

    // draw GrabZone for rotating
    pen.setColor(QColor(0, 0, 0, 127));
    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);
    painter.setBrush(QBrush(QColor(127, 127, 127, 127), Qt::SolidPattern));
    QPointF rotateLineFrom = (outerRect.topRight() + outerRect.topLeft()) / 2.0;
    QPointF rotateLineTo = (outerRect.topRight() + outerRect.topLeft()) / 2.0 - QPointF(0, m_rotateRectCenter - m_rotateRectRadius);
    painter.drawLine(rotateLineFrom, rotateLineTo);
    painter.drawEllipse(rotateLineTo - QPointF(0.0, m_rotateRectRadius), m_rotateRectRadius, m_rotateRectRadius);
  }
  painter.setRenderHint(QPainter::Antialiasing, false);

  painter.setTransform(paintTrans.inverted(), true);
}
bool NetPanelController::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::GraphicsSceneMousePress) {
        m_watched = qobject_cast<Plasma::ToolButton *>(watched);
    } else if (event->type() == QEvent::GraphicsSceneMouseRelease) {
        m_watched = 0;
    } else if (watched == m_moveButton && event->type() == QEvent::GraphicsSceneMouseMove) {
        QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(event);
        QRect screenGeom = Kephal::ScreenUtils::screenGeometry(m_containment->screen());

        //only move when the mouse cursor is out of the controller to avoid an endless reposition cycle
        if (geometry().contains(me->screenPos())) {
            return false;
        }

        if (!screenGeom.contains(me->screenPos())) {
            //move panel to new screen if dragged there
            int targetScreen = Kephal::ScreenUtils::screenId(me->screenPos());
            //kDebug() << "Moving panel from screen" << containment()->screen() << "to screen" << targetScreen;
            m_containment->setScreen(targetScreen);
            return false;
        }

        //create a dead zone so you can go across the middle without having it hop to one side
        float dzFactor = 0.35;
        QPoint offset = QPoint(screenGeom.width()*dzFactor,screenGeom.height()*dzFactor);
        QRect deadzone = QRect(screenGeom.topLeft()+offset, screenGeom.bottomRight()-offset);
        if (deadzone.contains(me->screenPos())) {
            //kDebug() << "In the deadzone:" << deadzone;
            return false;
        }

        const Plasma::Location oldLocation = m_containment->location();
        Plasma::Location newLocation = oldLocation;
        float screenAspect = float(screenGeom.height())/screenGeom.width();

        /* Use diagonal lines so we get predictable behavior when moving the panel
         * y=topleft.y+(x-topleft.x)*aspectratio   topright < bottomleft
         * y=bottomleft.y-(x-topleft.x)*aspectratio   topleft < bottomright
         */
        if (me->screenPos().y() < screenGeom.y()+(me->screenPos().x()-screenGeom.x())*screenAspect) {
            if (me->screenPos().y() < screenGeom.bottomLeft().y()-(me->screenPos().x()-screenGeom.x())*screenAspect) {
                if (m_containment->location() == Plasma::TopEdge) {
                    return false;
                } else {
                    newLocation = Plasma::TopEdge;
                }
            } else if (m_containment->location() == Plasma::RightEdge) {
                    return false;
            } else {
                newLocation = Plasma::RightEdge;
            }
        } else {
            if (me->screenPos().y() < screenGeom.bottomLeft().y()-(me->screenPos().x()-screenGeom.x())*screenAspect) {
                if (m_containment->location() == Plasma::LeftEdge) {
                    return false;
                } else {
                    newLocation = Plasma::LeftEdge;
                }
            } else if(m_containment->location() == Plasma::BottomEdge) {
                    return false;
            } else {
                newLocation = Plasma::BottomEdge;
            }
        }

        m_containment->setLocation(newLocation);

    } else if (watched == m_resizeButton && event->type() == QEvent::GraphicsSceneMouseMove) {
        QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(event);
        QPointF deltaPos(me->screenPos() - me->lastScreenPos());

        m_containment->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);

        switch (m_containment->location()) {
        case Plasma::LeftEdge:

            m_containment->setMinimumWidth(qBound((qreal)KIconLoader::SizeSmall, m_containment->size().width() + deltaPos.x(), (qreal)(KIconLoader::SizeEnormous*2)));
            m_containment->setMaximumWidth(m_containment->minimumWidth());

            break;
        case Plasma::RightEdge:

            m_containment->setMinimumWidth(qBound((qreal)KIconLoader::SizeSmall, m_containment->size().width() - deltaPos.x(), (qreal)(KIconLoader::SizeEnormous*2)));
            m_containment->setMaximumWidth(m_containment->minimumWidth());
            break;
        case Plasma::TopEdge:

            m_containment->setMinimumHeight(qBound((qreal)KIconLoader::SizeSmall, m_containment->size().height() + deltaPos.y(), (qreal)(KIconLoader::SizeEnormous*2)));
            m_containment->setMaximumHeight(m_containment->minimumHeight());
            break;
        case Plasma::BottomEdge:

            m_containment->setMinimumHeight(qBound((qreal)KIconLoader::SizeSmall, m_containment->size().height() - deltaPos.y(), (qreal)(KIconLoader::SizeEnormous*2)));
            m_containment->setMaximumHeight(m_containment->minimumHeight());
            break;
        default:
            break;
        }
    }
    return Plasma::Dialog::eventFilter(watched, event);
}
Example #22
0
/**
 * This function is used to create custom behaviour when clicking
 * on user/channel flags (e.g. showing the comment)
 */
void UserView::mouseReleaseEvent(QMouseEvent *evt) {
	QPoint clickPosition = evt->pos();

	QModelIndex idx = indexAt(clickPosition);
	if ((evt->button() == Qt::LeftButton) && idx.isValid()) {
		UserModel *userModel = qobject_cast<UserModel *>(model());
		ClientUser *clientUser = userModel->getUser(idx);
		Channel *channel = userModel->getChannel(idx);

		int commentFlagPxOffset = -UserDelegate::FLAG_DIMENSION;
		bool hasComment = false;

		if (clientUser && !clientUser->qbaCommentHash.isEmpty()) {
			hasComment = true;

			if (clientUser->bLocalIgnore)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bRecording)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bPrioritySpeaker)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bMute)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bSuppress)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bSelfMute)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bLocalMute)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bSelfDeaf)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->bDeaf)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (! clientUser->qsFriendName.isEmpty())
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;
			if (clientUser->iId >= 0)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;

		} else if (channel && !channel->qbaDescHash.isEmpty()) {
			hasComment = true;

			if (channel->bFiltered)
				commentFlagPxOffset -= UserDelegate::FLAG_DIMENSION;

		}

		if (hasComment) {
			QRect r = visualRect(idx);
			const int commentFlagPxPos = r.topRight().x() + commentFlagPxOffset;

			if ((clickPosition.x() >= commentFlagPxPos)
					&& (clickPosition.x() <= (commentFlagPxPos + UserDelegate::FLAG_DIMENSION))) {
				// Clicked comment icon
				QString str = userModel->data(idx, Qt::ToolTipRole).toString();
				if (str.isEmpty()) {
					userModel->bClicked = true;
				} else {
					QWhatsThis::showText(viewport()->mapToGlobal(r.bottomRight()), str, this);
					userModel->seenComment(idx);
				}
				return;
			}
		}
	}
	QTreeView::mouseReleaseEvent(evt);
}
void TestbedMainWindow::maskToleranceGraph(QPoint point)
{
    int x = point.x();
    int y = point.y();
    L_INFO_P("Starting the fill");

    //mGraphPlot->res
    if (!mMask->isValidCoord(y,x))
        return;

    vector<RGBColor> currentColor;
    switch (mUi->samplingComboBox->currentIndex())
    {
        case 0:
            currentColor.push_back(mImage->element(y,x));
            break;
        case 1:
            {
                int rad = mImageWidget->getImageRadius();
                qDebug() << "Radius is :" << rad;
                Vector3dd mean(0);
                int num = 0;

                for (int i = y - rad; i <= y + rad; i++ )
                {
                    double l = sqrt((rad * rad) - (i-y) * (i-y ));
                    for (int j = x - l; j <= x + l; j++)
                    {
                        if (!mImage->isValidCoord(i,j))
                        {
                            continue;
                        }

                        mean += mImage->element(i,j).toDouble();
                        num++;
                       // mImage->element(i,j) = RGBColor::Yellow();
                    }
                }

                mean /= num;
                currentColor.push_back(RGBColor(mean.x(), mean.y(), mean.z()));
                Vector2d<int> point = Vector2d<int>(x,y);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
            }
            break;
        case 2:
        default:
            {
                int rad = mImageWidget->getImageRadius();

                Vector2d<int> point;

                point = Vector2d<int>(x,y);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x + rad ,y);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x - rad ,y);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x,y + rad);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x,y + rad);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));

                point = Vector2d<int>(x + rad * 0.7 ,y + rad * 0.7);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x + rad * 0.7 ,y - rad * 0.7);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x - rad * 0.7 ,y - rad * 0.7);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));
                point = Vector2d<int>(x - rad * 0.7 ,y + rad * 0.7);
                if (mImage->isValidCoord(point)) currentColor.push_back(mImage->element(point));

                qDebug() << "Adding " << currentColor.size() << " points";
            }
            break;
    }


    QRect inputRect = mImageWidget->getInputRect();
    QRect maskRect = QRect(0,0,mMask->w - 1, mMask->h - 1);
    QRect workingRect = inputRect.intersected(maskRect);
    int totalArea = workingRect.height() * workingRect.width();

    vector<int> areas;
    G8Buffer *mMaskTmp = NULL;

    delete_safe(mMaskStore);
    mMaskStore = new G12Buffer(mMask->getSize());

    for (int i = 0; i < mUi->toleranceSpinBox->value(); i++)
    {
        delete_safe(mMaskTmp);
        mMaskTmp = new G8Buffer(mMask);
        ToleranceFinalPredicate predicate(
                mMaskTmp,
                currentColor,
                i,
                mImageWidget->getInputRect()
        );
        AbstractPainter<RGB24Buffer> painter(mImage);
        painter.floodFill(x,y, predicate);
        int area = mMaskTmp->countValues(255,
                workingRect.topLeft().x(),
                workingRect.topLeft().y(),
                workingRect.bottomRight().x(),
                workingRect.bottomRight().y()
        );
        qDebug() << "Processing tolerance:" << i << " area :" << area << " (" << ((double)area / totalArea) * 100 << "%)";
        areas.push_back(area);

        for (int y = 0; y < mMaskTmp->h; y++)
        {
            for (int x = 0; x < mMaskTmp->w; x++)
            {
                if (mMaskTmp->element(y,x) && mMaskStore->element(y,x) == 0) {
                    mMaskStore->element(y,x) = i;
                }
            }
        }

    }

    delete_safe(mMaskTmp);

    int toleranceMax = mUi->toleranceSpinBox->value();
    int toleranceMin = 0;
    for (int i = 0; i < areas.size() - 1 ; i++)
    {
        double part = ((double)areas[i + 1] / totalArea) * 100 ;
        double dpart = (((double)areas[i + 1] - areas[i] ) / totalArea) * 100;

        if (part > mUi->maximumSelectioSpinBox->value())
        {
            toleranceMax = i;
            break;
        }

        if (part > mUi->minimumSelectionSpinBox->value() && toleranceMin == 0)
        {
            toleranceMin = i;
        }

        if (part > mUi->minimumSelectionSpinBox->value() && dpart > mUi->spikeSpinBox->value())
        {
            toleranceMax = i - mUi->stepBackSpinBox->value();
            if (toleranceMax < toleranceMin) toleranceMax = toleranceMin;
            break;
        }
   }

    /* Draw result */
    mGraphPlot->addGraphPoint(0, 0, true);
    for (int i = areas.size() - 1; i >= 0; i--)
    {
        mGraphPlot->addGraphPoint(0, ((double)areas[i] / totalArea) * 100, true);

        if (i > 0)
        mGraphPlot->addGraphPoint(1, (((double)areas[i] - areas[i - 1]) / totalArea) * 100, true);

        if (i == toleranceMax) {
            mGraphPlot->addGraphPoint(2, 1, true);
        } else {
            mGraphPlot->addGraphPoint(2, 0, true);
        }

        mGraphPlot->addGraphPoint(3, mUi->spikeSpinBox->value(),true);

    }
    mGraphPlot->update();

    /*clean path*/
    mMaskTmp = new G8Buffer(mMask);
       ToleranceFinalPredicate predicate(
               mMaskTmp,
               currentColor,
               toleranceMax,
               mImageWidget->getInputRect()
       );
       AbstractPainter<RGB24Buffer> painter(mImage);
       painter.floodFill(x,y, predicate);

    mMask->fillWith(mMaskTmp);

    L_INFO_P("Fill finished");
}
Example #24
0
void DoubleTabWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    QRect r = rect();

    // draw top level tab bar
    r.setHeight(Utils::StyleHelper::navigationWidgetHeight());

    QPoint offset = window()->mapToGlobal(QPoint(0, 0)) - mapToGlobal(r.topLeft());
    QRect gradientSpan = QRect(offset, window()->size());
    Utils::StyleHelper::horizontalGradient(&painter, gradientSpan, r);

    painter.setPen(Utils::StyleHelper::borderColor());

    QColor lighter(255, 255, 255, 40);
    painter.drawLine(r.bottomLeft(), r.bottomRight());
    painter.setPen(lighter);
    painter.drawLine(r.topLeft(), r.topRight());

    QFontMetrics fm(font());
    int baseline = (r.height() + fm.ascent()) / 2 - 1;

    // top level title
    if (!m_title.isEmpty()) {
        painter.setPen(Utils::StyleHelper::panelTextColor());
        painter.drawText(MARGIN, baseline, m_title);
    }

    QLinearGradient grad(QPoint(0, 0), QPoint(0, r.height() + OTHER_HEIGHT - 1));
    grad.setColorAt(0, QColor(247, 247, 247));
    grad.setColorAt(1, QColor(205, 205, 205));

    // draw background of second bar
    painter.fillRect(QRect(0, r.height(), r.width(), OTHER_HEIGHT), grad);
    painter.setPen(QColor(0x505050));
    painter.drawLine(0, r.height() + OTHER_HEIGHT,
                     r.width(), r.height() + OTHER_HEIGHT);
    painter.setPen(Qt::white);
    painter.drawLine(0, r.height(),
                     r.width(), r.height());

    // top level tabs
    int x = m_title.isEmpty() ? 0 :
            2 * MARGIN + qMax(fm.width(m_title), MIN_LEFT_MARGIN);

    // calculate sizes
    QList<int> nameWidth;
    int width = x;
    int indexSmallerThanOverflow = -1;
    int indexSmallerThanWidth = -1;
    for (int i = 0; i < m_tabs.size(); ++i) {
        const Tab &tab = m_tabs.at(i);
        int w = fm.width(tab.name);
        nameWidth << w;
        width += 2 * MARGIN + w;
        if (width < r.width())
            indexSmallerThanWidth = i;
        if (width < r.width() - OVERFLOW_DROPDOWN_WIDTH)
            indexSmallerThanOverflow = i;
    }
    m_lastVisibleIndex = -1;
    m_currentTabIndices.resize(m_tabs.size());
    if (indexSmallerThanWidth == m_tabs.size() - 1) {
        // => everything fits
        for (int i = 0; i < m_tabs.size(); ++i)
            m_currentTabIndices[i] = i;
        m_lastVisibleIndex = m_tabs.size()-1;
    } else {
        // => we need the overflow thingy
        if (m_currentIndex <= indexSmallerThanOverflow) {
            // easy going, simply draw everything that fits
            for (int i = 0; i < m_tabs.size(); ++i)
                m_currentTabIndices[i] = i;
            m_lastVisibleIndex = indexSmallerThanOverflow;
        } else {
            // now we need to put the current tab into
            // visible range. for that we need to find the place
            // to put it, so it fits
            width = x;
            int index = 0;
            bool handledCurrentIndex = false;
            for (int i = 0; i < m_tabs.size(); ++i) {
                if (index != m_currentIndex) {
                    if (!handledCurrentIndex) {
                        // check if enough room for current tab after this one
                        if (width + 2 * MARGIN + nameWidth.at(index)
                                + 2 * MARGIN + nameWidth.at(m_currentIndex)
                                < r.width() - OVERFLOW_DROPDOWN_WIDTH) {
                            m_currentTabIndices[i] = index;
                            ++index;
                            width += 2 * MARGIN + nameWidth.at(index);
                        } else {
                            m_currentTabIndices[i] = m_currentIndex;
                            handledCurrentIndex = true;
                            m_lastVisibleIndex = i;
                        }
                    } else {
                        m_currentTabIndices[i] = index;
                        ++index;
                    }
                } else {
                    ++index;
                    --i;
                }
            }
        }
    }

    // actually draw top level tabs
    for (int i = 0; i <= m_lastVisibleIndex; ++i) {
        int actualIndex = m_currentTabIndices.at(i);
        Tab tab = m_tabs.at(actualIndex);
        if (actualIndex == m_currentIndex) {
            painter.setPen(Utils::StyleHelper::borderColor());
            painter.drawLine(x - 1, 0, x - 1, r.height() - 1);
            painter.fillRect(QRect(x, 0,
                                   2 * MARGIN + fm.width(tab.name),
                                   r.height() + 1),
                             grad);

            if (actualIndex != 0) {
                painter.setPen(QColor(255, 255, 255, 170));
                painter.drawLine(x, 0, x, r.height());
            }
            x += MARGIN;
            painter.setPen(Qt::black);
            painter.drawText(x, baseline, tab.name);
            x += nameWidth.at(actualIndex);
            x += MARGIN;
            painter.setPen(Utils::StyleHelper::borderColor());
            painter.drawLine(x, 0, x, r.height() - 1);
            painter.setPen(QColor(0, 0, 0, 20));
            painter.drawLine(x + 1, 0, x + 1, r.height() - 1);
            painter.setPen(QColor(255, 255, 255, 170));
            painter.drawLine(x - 1, 0, x - 1, r.height());
        } else {
            if (i == 0)
                drawFirstLevelSeparator(&painter, QPoint(x, 0), QPoint(x, r.height()-1));
            x += MARGIN;
            painter.setPen(Utils::StyleHelper::panelTextColor());
            painter.drawText(x + 1, baseline, tab.name);
            x += nameWidth.at(actualIndex);
            x += MARGIN;
            drawFirstLevelSeparator(&painter, QPoint(x, 0), QPoint(x, r.height()-1));
        }
    }

    // draw overflow button
    if (m_lastVisibleIndex < m_tabs.size() - 1) {
        QStyleOption opt;
        opt.rect = QRect(x, 0, OVERFLOW_DROPDOWN_WIDTH - 1, r.height() - 1);
        style()->drawPrimitive(QStyle::PE_IndicatorArrowDown,
                               &opt, &painter, this);
        drawFirstLevelSeparator(&painter, QPoint(x + OVERFLOW_DROPDOWN_WIDTH, 0),
                                QPoint(x + OVERFLOW_DROPDOWN_WIDTH, r.height()-1));
    }

    // second level tabs
    if (m_currentIndex != -1) {
        int y = r.height() + (OTHER_HEIGHT - m_left.height()) / 2.;
        int imageHeight = m_left.height();
        Tab currentTab = m_tabs.at(m_currentIndex);
        QStringList subTabs = currentTab.subTabs;
        x = 0;
        for (int i = 0; i < subTabs.size(); ++i) {
            x += MARGIN;
            int textWidth = fm.width(subTabs.at(i));
            if (currentTab.currentSubTab == i) {
                painter.setPen(Qt::white);
                painter.drawPixmap(x, y, m_left);
                painter.drawPixmap(QRect(x + SELECTION_IMAGE_WIDTH, y,
                                         textWidth, imageHeight),
                                   m_mid, QRect(0, 0, m_mid.width(), m_mid.height()));
                painter.drawPixmap(x + SELECTION_IMAGE_WIDTH + textWidth, y, m_right);
            } else {
                painter.setPen(Qt::black);
            }
            x += SELECTION_IMAGE_WIDTH;
            painter.drawText(x, y + (imageHeight + fm.ascent()) / 2. - 1,
                             subTabs.at(i));
            x += textWidth + SELECTION_IMAGE_WIDTH + MARGIN;
            drawSecondLevelSeparator(&painter, QPoint(x, y), QPoint(x, y + imageHeight));
        }
    }
}
Example #25
0
void WindowsModernStyle::drawControl( ControlElement element, const QStyleOption* option,
	QPainter* painter, const QWidget* widget ) const
{
	switch ( element ) {
		case CE_MenuBarEmptyArea:
			return;

		case CE_MenuBarItem:
			if ( option->state & QStyle::State_Sunken && option->state & QStyle::State_Enabled ) {
				painter->setPen( m_colorMenuBorder );
				QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() );
				gradient.setColorAt( 0.0, m_colorMenuTitleBegin );
				gradient.setColorAt( 1.0, m_colorMenuTitleEnd );
				painter->setBrush( gradient );
				painter->drawRect( option->rect.adjusted( 0, 0, -1, 0 ) );
			} else if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled ) {
				painter->setPen( m_colorItemBorder );
				QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() );
				gradient.setColorAt( 0.0, m_colorItemBackgroundBegin );
				gradient.setColorAt( 1.0, m_colorItemBackgroundEnd );
				painter->setBrush( gradient );
				painter->drawRect( option->rect.adjusted( 0, 0, -1, -1 ) );
			}
			if ( const QStyleOptionMenuItem* optionItem = qstyleoption_cast<const QStyleOptionMenuItem*>( option ) ) {
				int flags = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
				if ( !styleHint( SH_UnderlineShortcut, option, widget ) )
					flags |= Qt::TextHideMnemonic;
				if ( !optionItem->icon.isNull() ) {
					QPixmap pixmap = optionItem->icon.pixmap( pixelMetric( PM_SmallIconSize, option, widget ), QIcon::Normal );
					drawItemPixmap( painter, option->rect, flags, pixmap );
				} else {
					drawItemText( painter, option->rect, flags, option->palette, true, optionItem->text, QPalette::Text );
				}
			}
			return;

		case CE_MenuEmptyArea:
			painter->fillRect( option->rect, m_colorMenuBackground );
			return;

		case CE_MenuItem: {
			if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled ) {
				painter->setPen( m_colorItemBorder );
				painter->setBrush( m_colorItemBackgroundBegin );
				painter->drawRect( option->rect.adjusted( 1, 0, -3, -1 ) );
			} else {
				QLinearGradient gradient( QPoint( 0, 0 ), QPoint( 25, 0 ) );
				gradient.setColorAt( 0.0, m_colorBarBegin );
				gradient.setColorAt( 1.0, m_colorBarEnd );
				QRect margin = option->rect;
				margin.setWidth( 25 );
				painter->fillRect( margin, gradient );
				QRect background = option->rect;
				background.setLeft( margin.right() + 1 );
				painter->fillRect( background, m_colorMenuBackground );
			}
			if ( const QStyleOptionMenuItem* optionItem = qstyleoption_cast<const QStyleOptionMenuItem*>( option ) ) {
				if ( optionItem->menuItemType == QStyleOptionMenuItem::Separator ) {
					painter->setPen( m_colorSeparator );
					painter->drawLine( option->rect.left() + 32, ( option->rect.top() + option->rect.bottom() ) / 2,
						option->rect.right(), ( option->rect.top() + option->rect.bottom() ) / 2 );
					return;
				}
				QRect checkRect = option->rect.adjusted( 2, 1, -2, -2 );
				checkRect.setWidth( 20 );
				if ( optionItem->checked && option->state & QStyle::State_Enabled ) {
					painter->setPen( m_colorItemBorder );
					if ( option->state & QStyle::State_Selected && option->state & QStyle::State_Enabled )
						painter->setBrush( m_colorItemSunkenBegin );
					else
						painter->setBrush( m_colorItemCheckedBegin );
					painter->drawRect( checkRect );
				}
				if ( !optionItem->icon.isNull() ) {
					QIcon::Mode mode;
					if ( optionItem->state & State_Enabled )
						mode = ( optionItem->state & State_Selected ) ? QIcon::Active : QIcon::Normal;
					else
						mode = QIcon::Disabled;
					QIcon::State state = optionItem->checked ? QIcon::On : QIcon::Off;
					QPixmap pixmap = optionItem->icon.pixmap( pixelMetric( PM_SmallIconSize, option, widget ), mode, state );
					QRect rect = pixmap.rect();
					rect.moveCenter( checkRect.center() );
					painter->drawPixmap( rect.topLeft(), pixmap );
				} else if ( optionItem->checked ) {
					QStyleOption optionCheckMark;
					optionCheckMark.initFrom( widget );
					optionCheckMark.rect = checkRect;
					if ( !( option->state & State_Enabled ) )
						optionCheckMark.palette.setBrush( QPalette::Text, optionCheckMark.palette.brush( QPalette::Disabled, QPalette::Text ) );
					drawPrimitive( PE_IndicatorMenuCheckMark, &optionCheckMark, painter, widget );
				}
				QRect textRect = option->rect.adjusted( 32, 1, -16, -1 );
				int flags = Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
				if ( !styleHint( SH_UnderlineShortcut, option, widget ) )
					flags |= Qt::TextHideMnemonic;
				QString text = optionItem->text;
				int pos = text.indexOf( '\t' );
				if ( pos >= 0 ) {
					drawItemText( painter, textRect, flags | Qt::AlignRight, option->palette, option->state & State_Enabled,
						text.mid( pos + 1 ), QPalette::Text );
					text = text.left( pos );
				}
				drawItemText( painter, textRect, flags, option->palette, option->state & State_Enabled, text, QPalette::Text );
				if ( optionItem->menuItemType == QStyleOptionMenuItem::SubMenu ) {
					QStyleOption optionArrow;
					optionArrow.initFrom( widget );
					optionArrow.rect = option->rect.adjusted( 0, 4, -4, -4 );
					optionArrow.rect.setLeft( option->rect.right() - 12 );
					optionArrow.state = option->state & State_Enabled;
					drawPrimitive( PE_IndicatorArrowRight, &optionArrow, painter, widget );
				}
			}
			return;
		}

		case CE_ToolBar: {
			QRect rect = option->rect;
			bool vertical = false;
			if ( const QToolBar* toolBar = qobject_cast<const QToolBar*>( widget ) ) {
				vertical = ( toolBar->orientation() == Qt::Vertical );
				if ( vertical )
					rect.setBottom( toolBar->childrenRect().bottom() + 2 );
				else
					rect.setRight( toolBar->childrenRect().right() + 2 );
			}
			painter->save();
			QRegion region = rect.adjusted( 2, 0, -2, 0 );
			region += rect.adjusted( 0, 2, 0, -2 );
			region += rect.adjusted( 1, 1, -1, -1 );
			painter->setClipRegion( region );
			QLinearGradient gradient;
			if ( vertical )
				gradient = QLinearGradient( rect.topLeft(), rect.topRight() );
			else
				gradient = QLinearGradient( rect.topLeft(), rect.bottomLeft() );
			gradient.setColorAt( 0.0, m_colorBarBegin );
			gradient.setColorAt( 0.4, m_colorBarMiddle );
			gradient.setColorAt( 0.6, m_colorBarMiddle );
			gradient.setColorAt( 1.0, m_colorBarEnd );
			painter->fillRect( rect, gradient );

			painter->setPen( vertical ? m_colorBorderLight : m_colorBorder );
			painter->drawLine( rect.bottomLeft() + QPoint( 2, 0 ), rect.bottomRight() - QPoint( 2, 0 ) );
			painter->setPen( vertical ? m_colorBorder : m_colorBorderLight );
			painter->drawLine( rect.topRight() + QPoint( 0, 2 ), rect.bottomRight() - QPoint( 0, 2 ) );
			painter->setPen( m_colorBorderLight );
			painter->drawPoint( rect.bottomRight() - QPoint( 1, 1 ) );
			painter->restore();
			return;
		}

		case CE_DockWidgetTitle: {
			QLinearGradient gradient( option->rect.topLeft(), option->rect.bottomLeft() );
			gradient.setColorAt( 0.0, m_colorBarBegin );
			gradient.setColorAt( 1.0, m_colorBarEnd );
			painter->fillRect( option->rect, gradient );
			if ( const QStyleOptionDockWidget* optionDockWidget = qstyleoption_cast<const QStyleOptionDockWidget*>( option ) ) {
				QRect rect = option->rect.adjusted( 6, 0, -4, 0 );
				if ( optionDockWidget->closable )
					rect.adjust( 0, 0, -16, 0 );
				if ( optionDockWidget->floatable )
					rect.adjust( 0, 0, -16, 0 );
				QString text = painter->fontMetrics().elidedText( optionDockWidget->title, Qt::ElideRight, rect.width() );
				drawItemText( painter, rect, Qt::AlignLeft | Qt::AlignVCenter, option->palette,
					option->state & State_Enabled, text, QPalette::WindowText );
			}
			return;
		}

		case CE_TabBarTabShape:
			if ( isStyledTabBar( widget ) ) {
				bool firstTab = false;
				bool lastTab = false;
				bool bottom = false;
				if ( const QStyleOptionTab* optionTab = qstyleoption_cast<const QStyleOptionTab*>( option ) ) {
					if ( optionTab->position == QStyleOptionTab::Beginning )
						firstTab = true;
					else if ( optionTab->position == QStyleOptionTab::End )
						lastTab = true;
					else if ( optionTab->position == QStyleOptionTab::OnlyOneTab )
						firstTab = lastTab = true;
					if ( optionTab->shape == QTabBar::RoundedSouth )
						bottom = true;
				}
				QRect rect = option->rect;
				painter->save();
				if ( option->state & State_Selected ) {
					if ( bottom )
						rect.adjust( firstTab ? 0 : -2, -1, lastTab ? -1 : 1, -1 );
					else
						rect.adjust( firstTab ? 0 : -2, 0, lastTab ? -1 : 1, 1 );
				} else {
					if ( bottom ) {
						rect.adjust( 0, -1, lastTab ? -1 : 0, -2 );
						painter->setClipRect( rect.adjusted( 0, 1, 1, 1 ) );
					} else {
						rect.adjust( 0, 1, lastTab ? -1 : 0, 0 );
						painter->setClipRect( rect.adjusted( 0, 0, 1, 0 ) );
					}
				}
				QLinearGradient gradient;
				if ( bottom )
					gradient = QLinearGradient( rect.bottomLeft(), rect.topLeft() );
				else
					gradient = QLinearGradient( rect.topLeft(), rect.bottomLeft() );
				if ( option->state & State_Selected ) {
					gradient.setColorAt( 0.0, m_colorItemBackgroundBegin );
					gradient.setColorAt( 1.0, option->palette.window().color() );
					painter->setPen( m_colorBorder );
				} else if ( option->state & State_MouseOver && option->state & State_Enabled ) {
					gradient.setColorAt( 0.0, m_colorItemBackgroundBegin );
					gradient.setColorAt( 1.0, m_colorItemBackgroundEnd );
					painter->setPen( m_colorBorderLight );
				} else {
					gradient.setColorAt( 0.0, m_colorBarMiddle );
					gradient.setColorAt( 1.0, m_colorBarEnd );
					painter->setPen( m_colorBorderLight );
				}
				painter->setBrush( gradient );
				painter->drawRect( rect );
				painter->restore();
				return;
			}
			break;

		case CE_ToolBoxTabShape: {
			QRect rect = option->rect.adjusted( 0, 0, -1, -1 );
			QLinearGradient gradient( rect.topLeft(), rect.bottomLeft() );
			if ( option->state & QStyle::State_Sunken ) {
				gradient.setColorAt( 0.0, m_colorItemSunkenBegin );
				gradient.setColorAt( 1.0, m_colorItemSunkenEnd );
				painter->setPen( m_colorBorder );
			} else if ( option->state & State_MouseOver && option->state & State_Enabled ) {
				gradient.setColorAt( 0.0, m_colorItemBackgroundBegin );
				gradient.setColorAt( 1.0, m_colorItemBackgroundEnd );
				painter->setPen( m_colorBorder );
			} else {
				gradient.setColorAt( 0.0, m_colorBarMiddle );
				gradient.setColorAt( 1.0, m_colorBarEnd );
				painter->setPen( m_colorBorderLight );
			}
			painter->setBrush( gradient );
			painter->drawRect( rect );
			return;
		}

		case CE_Splitter:
			if ( qobject_cast<const QMainWindow*>( widget->window() ) )
				return;
			break;

		default:
			break;
	}

	if ( useVista() )
		QWindowsVistaStyle::drawControl( element, option, painter, widget );
	else
		QWindowsXPStyle::drawControl( element, option, painter, widget );
}
Example #26
0
void
AlbumItemDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    AlbumItem* item = m_model->sourceModel()->itemFromIndex( m_model->mapToSource( index ) );
    if ( !item )
        return;

    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, QModelIndex() );
    qApp->style()->drawControl( QStyle::CE_ItemViewItem, &opt, painter );

    painter->save();
    painter->setRenderHint( QPainter::Antialiasing );

    if ( !( option.state & QStyle::State_Selected ) )
    {
        QRect shadowRect = option.rect.adjusted( 5, 4, -5, -40 );
        painter->setPen( QColor( 90, 90, 90 ) );
        painter->drawRoundedRect( shadowRect, 0.5, 0.5 );

        QPen shadowPen( QColor( 30, 30, 30 ) );
        shadowPen.setWidth( 0.4 );
        painter->drawLine( shadowRect.bottomLeft() + QPoint( -1, 2 ), shadowRect.bottomRight() + QPoint( 1, 2 ) );

        shadowPen.setColor( QColor( 160, 160, 160 ) );
        painter->setPen( shadowPen );
        painter->drawLine( shadowRect.topLeft() + QPoint( -1, 2 ), shadowRect.bottomLeft() + QPoint( -1, 2 ) );
        painter->drawLine( shadowRect.topRight() + QPoint( 2, 2 ), shadowRect.bottomRight() + QPoint( 2, 2 ) );
        painter->drawLine( shadowRect.bottomLeft() + QPoint( 0, 3 ), shadowRect.bottomRight() + QPoint( 0, 3 ) );

        shadowPen.setColor( QColor( 180, 180, 180 ) );
        painter->setPen( shadowPen );
        painter->drawLine( shadowRect.topLeft() + QPoint( -2, 3 ), shadowRect.bottomLeft() + QPoint( -2, 1 ) );
        painter->drawLine( shadowRect.topRight() + QPoint( 3, 3 ), shadowRect.bottomRight() + QPoint( 3, 1 ) );
        painter->drawLine( shadowRect.bottomLeft() + QPoint( 0, 4 ), shadowRect.bottomRight() + QPoint( 0, 4 ) );
    }

    QPixmap cover;
    if ( !item->album().isNull() )
    {
        cover.loadFromData( item->album()->cover() );
    }
    else if ( !item->artist().isNull() )
    {
        cover.loadFromData( item->artist()->cover() );
    }

    if ( cover.isNull() )
        cover = m_defaultCover;

    QRect r = option.rect.adjusted( 6, 5, -6, -41 );

    if ( option.state & QStyle::State_Selected )
    {
#if defined(Q_WS_MAC) || defined(Q_WS_WIN)
        painter->save();
        painter->setRenderHint( QPainter::Antialiasing );

        QPainterPath border;
        border.addRoundedRect( r.adjusted( -2, -2, 2, 2 ), 3, 3 );
        QPen borderPen( QColor( 86, 170, 243 ) );
        borderPen.setWidth( 5 );
        painter->setPen( borderPen );
        painter->drawPath( border );

        painter->restore();
#else
        opt.palette.setColor( QPalette::Text, opt.palette.color( QPalette::HighlightedText ) );
#endif
    }

    QPixmap scover;
    if ( m_cache.contains( cover.cacheKey() ) )
    {
        scover = m_cache.value( cover.cacheKey() );
    }
    else
    {
        scover = cover.scaled( r.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation );
        m_cache.insert( cover.cacheKey(), scover );
    }
    painter->drawPixmap( r, scover );

    painter->setPen( opt.palette.color( QPalette::Text ) );
    QTextOption to;
    to.setWrapMode( QTextOption::NoWrap );

    QString text;
    QFont font = opt.font;
    font.setPixelSize( 11 );
    QFont boldFont = font;
    boldFont.setBold( true );

    QRect textRect = option.rect.adjusted( 0, option.rect.height() - 32, 0, -2 );

    QString name;
    if ( !item->album().isNull() )
        name = item->album()->name();
    else if ( !item->artist().isNull() )
        name = item->artist()->name();

    painter->setFont( boldFont );
    bool oneLiner = false;
    if ( item->album().isNull() || item->album()->artist().isNull() )
        oneLiner = true;
    else
        oneLiner = ( textRect.height() / 2 < painter->fontMetrics().boundingRect( item->album()->name() ).height() ||
                     textRect.height() / 2 < painter->fontMetrics().boundingRect( item->album()->artist()->name() ).height() );

    if ( oneLiner )
    {
        to.setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );
        text = painter->fontMetrics().elidedText( name, Qt::ElideRight, textRect.width() - 3 );
        painter->drawText( textRect, text, to );
    }
    else
    {
        to.setAlignment( Qt::AlignHCenter | Qt::AlignTop );
        text = painter->fontMetrics().elidedText( item->album()->name(), Qt::ElideRight, textRect.width() - 3 );
        painter->drawText( textRect, text, to );

        // If the user is hovering over an artist rect, draw a background so she knows it's clickable
        QRect r = textRect;
        r.setTop( r.bottom() - painter->fontMetrics().height() );
        r.adjust( 4, 0, -4, -1 );
        if ( m_hoveringOver == index )
        {
            TomahawkUtils::drawQueryBackground( painter, opt.palette, r, 1.1 );
            painter->setPen( opt.palette.color( QPalette::HighlightedText ) );
        }
        else
        {
            if ( !( option.state & QStyle::State_Selected ) )
#ifdef Q_WS_MAC
                painter->setPen( opt.palette.color( QPalette::Dark ).darker( 200 ) );
#else
                painter->setPen( opt.palette.color( QPalette::Dark ) );
#endif
        }

        to.setAlignment( Qt::AlignHCenter | Qt::AlignBottom );
        text = painter->fontMetrics().elidedText( item->album()->artist()->name(), Qt::ElideRight, textRect.width() - 10 );
        painter->drawText( textRect.adjusted( 5, -1, -5, -1 ), text, to );

        // Calculate rect of artist on-hover button click area
        m_artistNameRects[ index ] = r;
    }

    painter->restore();
}
Example #27
0
void QAbstractScrollAreaPrivate::layoutChildren()
{
    Q_Q(QAbstractScrollArea);
    bool needh = (hbarpolicy == Qt::ScrollBarAlwaysOn
                  || (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum()));

    bool needv = (vbarpolicy == Qt::ScrollBarAlwaysOn
                  || (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum()));

#ifdef Q_WS_MAC
    QWidget * const window = q->window();

    // Use small scroll bars for tool windows, to match the native size grip.
    bool hbarIsSmall = hbar->testAttribute(Qt::WA_MacSmallSize);
    bool vbarIsSmall = vbar->testAttribute(Qt::WA_MacSmallSize);
    const Qt::WindowType windowType = window->windowType();
    if (windowType == Qt::Tool) {
        if (!hbarIsSmall) {
            hbar->setAttribute(Qt::WA_MacMiniSize, false);
            hbar->setAttribute(Qt::WA_MacNormalSize, false);
            hbar->setAttribute(Qt::WA_MacSmallSize, true);
        }
        if (!vbarIsSmall) {
            vbar->setAttribute(Qt::WA_MacMiniSize, false);
            vbar->setAttribute(Qt::WA_MacNormalSize, false);
            vbar->setAttribute(Qt::WA_MacSmallSize, true);
        }
    } else {
        if (hbarIsSmall) {
            hbar->setAttribute(Qt::WA_MacMiniSize, false);
            hbar->setAttribute(Qt::WA_MacNormalSize, false);
            hbar->setAttribute(Qt::WA_MacSmallSize, false);
        }
        if (vbarIsSmall) {
            vbar->setAttribute(Qt::WA_MacMiniSize, false);
            vbar->setAttribute(Qt::WA_MacNormalSize, false);
            vbar->setAttribute(Qt::WA_MacSmallSize, false);
        }
     }
#endif

    const int hsbExt = hbar->sizeHint().height();
    const int vsbExt = vbar->sizeHint().width();
    const QPoint extPoint(vsbExt, hsbExt);
    const QSize extSize(vsbExt, hsbExt);

    const QRect widgetRect = q->rect();
    QStyleOption opt(0);
    opt.init(q);

    const bool hasCornerWidget = (cornerWidget != 0);

// If the scroll bars are at the very right and bottom of the window we
// move their positions to be aligned with the size grip.
#ifdef Q_WS_MAC
    // Check if a native sizegrip is present.
    bool hasMacReverseSizeGrip = false;
    bool hasMacSizeGrip = false;
    bool nativeGripPresent = false;
    if (q->testAttribute(Qt::WA_WState_Created))
        nativeGripPresent = qt_mac_checkForNativeSizeGrip(q);

    if (nativeGripPresent) {
        // Look for a native size grip at the visual window bottom right and at the
        // absolute window bottom right. In reverse mode, the native size grip does not
        // swich side, so we need to check if it is on the "wrong side".
        const QPoint scrollAreaBottomRight = q->mapTo(window, widgetRect.bottomRight() - QPoint(frameWidth, frameWidth));
        const QPoint windowBottomRight = window->rect().bottomRight();
        const QPoint visualWindowBottomRight = QStyle::visualPos(opt.direction, opt.rect, windowBottomRight);
        const QPoint offset = windowBottomRight - scrollAreaBottomRight;
        const QPoint visualOffset = visualWindowBottomRight - scrollAreaBottomRight;
        hasMacSizeGrip = (visualOffset.manhattanLength() < vsbExt);
        hasMacReverseSizeGrip = (hasMacSizeGrip == false && (offset.manhattanLength() < hsbExt));
    }
#endif

    QPoint cornerOffset(needv ? vsbExt : 0, needh ? hsbExt : 0);
    QRect controlsRect;
    QRect viewportRect;

    // In FrameOnlyAroundContents mode the frame is drawn between the controls and
    // the viewport, else the frame rect is equal to the widget rect.
    if ((frameStyle != QFrame::NoFrame) &&
        q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, q)) {
        controlsRect = widgetRect;
        const int extra = q->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, q);
        const QPoint cornerExtra(needv ? extra : 0, needh ? extra : 0);
        QRect frameRect = widgetRect;
        frameRect.adjust(0, 0, -cornerOffset.x() - cornerExtra.x(), -cornerOffset.y() - cornerExtra.y());
        q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, frameRect));
        // The frame rect needs to be in logical coords, however we need to flip
        // the contentsRect back before passing it on to the viewportRect
        // since the viewportRect has its logical coords calculated later.
        viewportRect = QStyle::visualRect(opt.direction, opt.rect, q->contentsRect());
    } else {
        q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, widgetRect));
        controlsRect = q->contentsRect();
        viewportRect = QRect(controlsRect.topLeft(), controlsRect.bottomRight() - cornerOffset);
    }

    // If we have a corner widget and are only showing one scroll bar, we need to move it
    // to make room for the corner widget.
    if (hasCornerWidget && (needv || needh))
        cornerOffset =  extPoint;

#ifdef Q_WS_MAC
    // Also move the scroll bars if they are covered by the native Mac size grip.
    if (hasMacSizeGrip)
        cornerOffset =  extPoint;
#endif

    // The corner point is where the scroll bar rects, the corner widget rect and the
    // viewport rect meets.
    const QPoint cornerPoint(controlsRect.bottomRight() + QPoint(1, 1) - cornerOffset);

    // Some styles paints the corner if both scorllbars are showing and there is
    // no corner widget. Also, on the Mac we paint if there is a native
    // (transparent) sizegrip in the area where a corner widget would be.
    if ((needv && needh && hasCornerWidget == false)
        || ((needv || needh) 
#ifdef Q_WS_MAC
        && hasMacSizeGrip
#endif
        )
    ) {
        cornerPaintingRect = QStyle::visualRect(opt.direction, opt.rect, QRect(cornerPoint, extSize));
    } else {
        cornerPaintingRect = QRect();
    }

#ifdef Q_WS_MAC
    if (hasMacReverseSizeGrip)
        reverseCornerPaintingRect = QRect(controlsRect.bottomRight() + QPoint(1, 1) - extPoint, extSize);
    else
        reverseCornerPaintingRect = QRect();
#endif

    if (needh) {
        QRect horizontalScrollBarRect(QPoint(controlsRect.left(), cornerPoint.y()), QPoint(cornerPoint.x() - 1, controlsRect.bottom()));
#ifdef Q_WS_MAC
        if (hasMacReverseSizeGrip)
            horizontalScrollBarRect.adjust(vsbExt, 0, 0, 0);
#endif
        scrollBarContainers[Qt::Horizontal]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, horizontalScrollBarRect));
        scrollBarContainers[Qt::Horizontal]->raise();
    }

    if (needv) {
        const QRect verticalScrollBarRect  (QPoint(cornerPoint.x(), controlsRect.top()),  QPoint(controlsRect.right(), cornerPoint.y() - 1));
        scrollBarContainers[Qt::Vertical]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, verticalScrollBarRect));
        scrollBarContainers[Qt::Vertical]->raise();
    }

    if (cornerWidget) {
        const QRect cornerWidgetRect(cornerPoint, controlsRect.bottomRight());
        cornerWidget->setGeometry(QStyle::visualRect(opt.direction, opt.rect, cornerWidgetRect));
    }

    scrollBarContainers[Qt::Horizontal]->setVisible(needh);
    scrollBarContainers[Qt::Vertical]->setVisible(needv);

    if (q->isRightToLeft())
        viewportRect.adjust(right, top, -left, -bottom);
    else
        viewportRect.adjust(left, top, -right, -bottom);

    viewport->setGeometry(QStyle::visualRect(opt.direction, opt.rect, viewportRect)); // resize the viewport last
}
/*!
    \reimp
*/
void QTransformedScreen::blit(const QImage &image, const QPoint &topLeft,
                              const QRegion &region)
{
    const Transformation trans = d_ptr->transformation;
    if (trans == None) {
        QProxyScreen::blit(image, topLeft, region);
        return;
    }

    const QVector<QRect> rects = region.rects();
    const QRect bound = QRect(0, 0, QScreen::w, QScreen::h)
                        & QRect(topLeft, image.size());

    BlitFunc func = 0;
#ifdef QT_QWS_DEPTH_GENERIC
    if (d_ptr->doGenericColors && depth() == 16) {
        if (image.depth() == 16)
            SET_BLIT_FUNC(qrgb_generic16, quint16, trans, func);
        else
            SET_BLIT_FUNC(qrgb_generic16, quint32, trans, func);
    } else
#endif
    switch (depth()) {
#ifdef QT_QWS_DEPTH_32
    case 32:
#ifdef QT_QWS_DEPTH_16
        if (image.depth() == 16)
            SET_BLIT_FUNC(quint32, quint16, trans, func);
        else
#endif
            SET_BLIT_FUNC(quint32, quint32, trans, func);
        break;
#endif
#if defined(QT_QWS_DEPTH_24) || defined(QT_QWS_DEPTH18)
    case 24:
    case 18:
        SET_BLIT_FUNC(quint24, quint24, trans, func);
        break;
#endif
#if defined(QT_QWS_DEPTH_16) || defined(QT_QWS_DEPTH_15) || defined(QT_QWS_DEPTH_12)
    case 16:
    case 15:
    case 12:
        if (image.depth() == 16)
            SET_BLIT_FUNC(quint16, quint16, trans, func);
        else
            SET_BLIT_FUNC(quint16, quint32, trans, func);
        break;
#endif
#ifdef QT_QWS_DEPTH_8
    case 8:
        if (image.depth() == 16)
            SET_BLIT_FUNC(quint8, quint16, trans, func);
        else
            SET_BLIT_FUNC(quint8, quint32, trans, func);
        break;
#endif
    default:
        return;
    }
    if (!func)
        return;

    QWSDisplay::grab();
    for (int i = 0; i < rects.size(); ++i) {
        const QRect r = rects.at(i) & bound;

        QPoint dst;
        switch (trans) {
        case Rot90:
            dst = mapToDevice(r.topRight(), QSize(w, h));
            break;
        case Rot180:
            dst = mapToDevice(r.bottomRight(), QSize(w, h));
            break;
        case Rot270:
            dst = mapToDevice(r.bottomLeft(), QSize(w, h));
            break;
        default:
            break;
        }
        func(this, image, r.translated(-topLeft), dst);
    }
    QWSDisplay::ungrab();

}
Example #29
0
void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
{
    QStyleOptionTabV2 tab;
    initStyleOption(&tab, tabIndex);
    QRect rect = tab.rect;
    painter->save();


    bool selected = tab.state & QStyle::State_Selected;
    bool hover = tab.state & QStyle::State_MouseOver;

#ifdef Q_WS_MAC
    hover = false; // Dont hover on Mac
#endif

    QColor background = QColor(0, 0, 0, 10);
    QColor hoverColor;

    if (hover) {
        hoverColor = QColor(255, 255, 255, m_hoverControl.currentFrame()*2);
    }

    QColor light = QColor(255, 255, 255, 40);
    QColor dark = QColor(0, 0, 0, 60);

    if (selected) {
        QLinearGradient selectedGradient(rect.topLeft(), QPoint(rect.center().x(), rect.bottom()));
        selectedGradient.setColorAt(0, Qt::white);
        selectedGradient.setColorAt(0.3, Qt::white);
        selectedGradient.setColorAt(0.7, QColor(230, 230, 230));

        painter->fillRect(rect, selectedGradient);
        painter->setPen(QColor(200, 200, 200));
        painter->drawLine(rect.topLeft(), rect.topRight());
        painter->setPen(QColor(150, 160, 200));
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
    } else {
        painter->fillRect(tab.rect, background);
        if (hover)
            painter->fillRect(tab.rect, hoverColor);
        painter->setPen(QPen(light, 0));
        painter->drawLine(rect.topLeft(), rect.topRight());
        painter->setPen(QPen(dark, 0));
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
    }

    QString tabText(tab.text);
    QRect tabTextRect(tab.rect);
    QRect tabIconRect(tab.rect);
    QFont boldFont(painter->font());
    boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
    boldFont.setBold(true);
    painter->setFont(boldFont);
    painter->setPen(selected ? StyleHelper::panelTextColor() : QColor(30, 30, 30, 80));
    int textFlags = Qt::AlignCenter | Qt::AlignBottom | Qt::ElideRight | Qt::TextWordWrap;
    painter->drawText(tabTextRect, textFlags, tabText);
    painter->setPen(selected ? QColor(60, 60, 60) : StyleHelper::panelTextColor());
    int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
    tabIconRect.adjust(0, 4, 0, -textHeight);
    style()->drawItemPixmap(painter, tabIconRect, Qt::AlignCenter | Qt::AlignVCenter,
                            tab.icon.pixmap(QSize(64, 64)));
    painter->translate(0, -1);
    painter->drawText(tabTextRect, textFlags, tabText);
    painter->restore();
}
Example #30
0
void
GetNewStuffDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, index );

    QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget );

    painter->setRenderHint( QPainter::Antialiasing );

    QFont titleFont = opt.font;
    titleFont.setBold( true );
    titleFont.setPointSize( titleFont.pointSize() + 2 );
    QFontMetrics titleMetrics( titleFont );

    QFont authorFont = opt.font;
    authorFont.setItalic( true );
    authorFont.setPointSize( authorFont.pointSize() - 1 );
    QFontMetrics authorMetrics( authorFont );

    QFont descFont = authorFont;
    descFont.setItalic( false );
    QFontMetrics descMetrics( descFont );

    QFont installFont = opt.font;
    installFont.setPointSize( installFont.pointSize() - 1 );
    QFontMetrics installMetrics( descFont );

    const int height = opt.rect.height();
    const int center = height / 2 + opt.rect.top();

    // Pixmap
    QPixmap p = index.data( Qt::DecorationRole ).value< QPixmap >();
    const int pixmapWidth = height - 2*PADDING;
    QRect pixmapRect( PADDING, PADDING + opt.rect.top(), pixmapWidth, pixmapWidth );
    if ( p.isNull() ) // default image... TODO
        p = m_defaultCover;
    else
        p = p.scaled( pixmapRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation );

    painter->drawPixmap( pixmapRect, p );

    // Go from right edge now, stars, install button, and downloaded info

    // install / status button
    AtticaManager::ResolverState state = static_cast< AtticaManager::ResolverState >( index.data( GetNewStuffModel::StateRole ).toInt() );
    QString actionText;
    switch( state )
    {
        case AtticaManager::Uninstalled:
            actionText = tr( "Install" );
            break;
        case AtticaManager::Installing:
            actionText = tr( "Installing" );
            break;
        case AtticaManager::Upgrading:
            actionText = tr( "Upgrading" );
            break;
        case AtticaManager::Failed:
            actionText = tr( "Failed" );
            break;
        case AtticaManager::Installed:
            actionText = tr( "Uninstall" );
            break;
        case AtticaManager::NeedsUpgrade:
            actionText = tr( "Upgrade" );
            break;
    }

    const int btnWidth = m_widestTextWidth + 7;
    const int leftEdge = opt.rect.width() - PADDING - btnWidth - 3;
    const QRect btnRect( leftEdge, center - ( installMetrics.height() + 4 ) / 2, btnWidth, installMetrics.height() + 4 );
    m_cachedButtonRects[ QPair<int, int>(index.row(), index.column()) ] = btnRect;

    QPen saved = painter->pen();
    painter->setPen( opt.palette.color( QPalette::Active, QPalette::AlternateBase ) );

    QPainterPath btnPath;
    const int radius = 3;
    //btnPath.addRoundedRect( btnRect, 3, 3 );
    // draw top half gradient
    const int btnCenter = btnRect.bottom() - ( btnRect.height() / 2 );
    btnPath.moveTo( btnRect.left(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnRect.top() + radius );
    btnPath.quadTo( QPoint( btnRect.topLeft() ), QPoint( btnRect.left() + radius, btnRect.top() ) );
    btnPath.lineTo( btnRect.right() - radius, btnRect.top() );
    btnPath.quadTo( QPoint( btnRect.topRight() ), QPoint( btnRect.right(), btnRect.top() + radius ) );
    btnPath.lineTo( btnRect.right(),btnCenter );
    btnPath.lineTo( btnRect.left(), btnCenter );

    QLinearGradient g;
    g.setColorAt( 0, QColor(54, 127, 211) );
    g.setColorAt( 0.5, QColor(43, 104, 182) );
    //painter->setPen( bg.darker() );
    painter->fillPath( btnPath, g );
    //painter->drawPath( btnPath );

    btnPath = QPainterPath();
    btnPath.moveTo( btnRect.left(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnRect.bottom() - radius );
    btnPath.quadTo( QPoint( btnRect.bottomLeft() ), QPoint( btnRect.left() + radius, btnRect.bottom() ) );
    btnPath.lineTo( btnRect.right() - radius, btnRect.bottom() );
    btnPath.quadTo( QPoint( btnRect.bottomRight() ), QPoint( btnRect.right(), btnRect.bottom() - radius ) );
    btnPath.lineTo( btnRect.right(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnCenter );

    g.setColorAt( 0, QColor(34, 85, 159) );
    g.setColorAt( 0.5, QColor(35, 79, 147) );
    painter->fillPath( btnPath, g );

    painter->setFont( installFont );
    painter->drawText( btnRect, Qt::AlignCenter, actionText );

    painter->setPen( saved );

    // rating stars
    int rating = index.data( GetNewStuffModel::RatingRole ).toInt();
    const int ratingWidth = 5 * ( m_ratingStarPositive.width() + PADDING_BETWEEN_STARS );
    int runningEdge = ( btnRect.right() - btnRect.width() / 2 ) - ratingWidth / 2;
    for ( int i = 1; i < 6; i++ )
    {
        QRect r( runningEdge, btnRect.top() - m_ratingStarPositive.height() - PADDING, m_ratingStarPositive.width(), m_ratingStarPositive.height() );
        if ( i == 1 )
            m_cachedStarRects[ QPair<int, int>(index.row(), index.column()) ] = r;

        const bool userHasRated = index.data( GetNewStuffModel::UserHasRatedRole ).toBool();
        if ( !userHasRated && // Show on-hover animation if the user hasn't rated it yet, and is hovering over it
             m_hoveringOver > -1 &&
             m_hoveringItem == index )
        {
            if ( i <= m_hoveringOver ) // positive star
                painter->drawPixmap( r, m_onHoverStar );
            else
                painter->drawPixmap( r, m_ratingStarNegative );
        }
        else
        {
            if ( i <= rating ) // positive or rated star
            {
                if ( userHasRated )
                    painter->drawPixmap( r, m_onHoverStar );
                else
                    painter->drawPixmap( r, m_ratingStarPositive );
            }
            else
                painter->drawPixmap( r, m_ratingStarNegative );
        }
        runningEdge += m_ratingStarPositive.width() + PADDING_BETWEEN_STARS;
    }

    // downloaded num times, underneath button
    QString count = tr( "%1 downloads" ).arg( index.data( GetNewStuffModel::DownloadCounterRole ).toInt() );
    const QRect countRect( btnRect.left(), btnRect.bottom() + PADDING, btnRect.width(), opt.rect.bottom() - PADDING - btnRect.bottom() );
    QFont countFont = descFont;
    countFont.setPointSize( countFont.pointSize() - 2 );
    countFont.setBold( true );
    painter->setFont( countFont );
    painter->drawText( countRect, Qt::AlignCenter | Qt::TextWordWrap, count );

    // author and version
    QString author = index.data( GetNewStuffModel::AuthorRole ).toString();
    const int authorWidth = authorMetrics.width( author );
    const int topTextLine = opt.rect.top() + PADDING;
    const QRect authorRect( btnRect.x() - 3*PADDING - authorWidth, topTextLine, authorWidth + 6, authorMetrics.height() );
    painter->setFont( authorFont );
    painter->drawText( authorRect, Qt::AlignCenter, author );

    const QRect versionRect = authorRect.translated( 0, authorRect.height() );
    QString version = index.data( GetNewStuffModel::VersionRole ).toString();
    painter->drawText( versionRect, Qt::AlignCenter, version );

    // title
    QString title = index.data( Qt::DisplayRole ).toString();
    const int rightTitleEdge = authorRect.left() - PADDING;
    const int leftTitleEdge = pixmapRect.right() + PADDING;
    const QRect textRect( leftTitleEdge, topTextLine, rightTitleEdge - leftTitleEdge, versionRect.bottom() - opt.rect.top() - PADDING );
    painter->setFont( titleFont );
    painter->drawText( textRect, Qt::AlignVCenter | Qt::AlignLeft, title );

    // description
    QString desc = index.data( GetNewStuffModel::DescriptionRole ).toString();
    const int descWidth = btnRect.left() - leftTitleEdge - PADDING;
    const QRect descRect( leftTitleEdge, versionRect.bottom(), descWidth, opt.rect.bottom() - versionRect.bottom() + PADDING );
    painter->setFont( descFont );
    painter->drawText( descRect, Qt::AlignLeft | Qt::TextWordWrap, desc );
}