Example #1
0
void UBRubberBand::mouseMoveEvent(QMouseEvent *event)
{
    determineResizingMode(event->pos());

    if (mMouseIsPressed)
    {
        UBBoardView *view = UBApplication::boardController->controlView();
        QRect currentGeometry = geometry();

        QPoint pressPoint(event->pos());
        QPoint pressPointGlobal(view->mapToGlobal(pressPoint));
        QPoint prevPressPointGlobal(view->mapToGlobal(mLastPressedPoint));
        QPoint movePointGlogal = (view->mapToGlobal(mLastMousePos));

        QPoint topLeftResizeVector(pressPointGlobal - prevPressPointGlobal);
        QPoint rightBottomResizeVector(pressPointGlobal - movePointGlogal);

        bool bGeometryChange = true;

        switch(mResizingMode)
        {
        case None:
            {
                QPointF itemsMoveVector(view->mapToScene(pressPointGlobal) - view->mapToScene(prevPressPointGlobal));

                move(pos()+pressPointGlobal - prevPressPointGlobal);
                view->moveRubberedItems(itemsMoveVector);

                bGeometryChange = false;
                break;
            }

        case Top:
            {
                currentGeometry.setY(currentGeometry.y()+topLeftResizeVector.y());
            }break;

        case Bottom:
            {
                currentGeometry.setHeight(currentGeometry.height()+rightBottomResizeVector.y());
            }break;

        case Left:
            {
                currentGeometry.setX(currentGeometry.x()+topLeftResizeVector.x());
            }break;
        case Right:
            {
                currentGeometry.setWidth(currentGeometry.width()+rightBottomResizeVector.x());
            }break;

        case TopLeft:
            {
                currentGeometry.setX(currentGeometry.x()+topLeftResizeVector.x());  
                currentGeometry.setY(currentGeometry.y()+topLeftResizeVector.y());
            }break;

        case TopRight:
            {
                currentGeometry.setY(currentGeometry.y()+topLeftResizeVector.y());  
                currentGeometry.setWidth(currentGeometry.width()+rightBottomResizeVector.x());                
            }
            break;

        case BottomLeft:
            {
                currentGeometry.setX(currentGeometry.x()+topLeftResizeVector.x());
                currentGeometry.setHeight(currentGeometry.height()+rightBottomResizeVector.y());  
            }break;

        case BottomRight:
            {
                currentGeometry.setWidth(currentGeometry.width()+rightBottomResizeVector.x());
                currentGeometry.setHeight(currentGeometry.height()+rightBottomResizeVector.y());        
            }break;
        
        }
        if(bGeometryChange)
        {   
            setGeometry(currentGeometry);
        }

        mLastMousePos = event->pos();
    }

    QRubberBand::mouseMoveEvent(event);
} 
Example #2
0
void MyListWidget::mousePressEvent( QMouseEvent * event  ) {
    QPoint pos = event->pos();
    QPersistentModelIndex index = indexAt(pos);

    QString path = index.data(ROLE_ITEM_PATH).toString();
    if(event->button() != Qt::LeftButton){
        QPoint globalPos = QWidget::mapToGlobal(pos);
        emit showOptionsMenu(path,globalPos);
        //emit pressed(index);
        return;

    }

    //Later...
    //if(event->button() == Qt::RightButton){ }

    QRect containingRect = this->geometry();
    containingRect.setHeight(UI_DEFAULT_ITEM_HEIGHT);
    containingRect.moveTop(0);

    QRect pinRect = IconDelegate::getPinItemRect(containingRect);
    QListWidgetItem*  listWidgetItem = item(index.row());

    QPoint localPos = pos;
    localPos.setY(pos.y() % UI_DEFAULT_ITEM_HEIGHT);

    if(pinRect.contains(localPos)){
        CatItem pinItem(addPrefix(OPERATION_PREFIX,PIN_OPERATION_NAME));

        if(!(listWidgetItem->data((ROLE_ITEM_PINNED)).toBool())){
            listWidgetItem->setData((ROLE_ITEM_PINNED),true);
        } else {listWidgetItem->setData((ROLE_ITEM_PINNED),false);}

        //emit listItemAction(path, pinItem);
        //frickin signal not going through
        gMainWidget->operateOnItem(path,pinItem);
        return;
    }

    QRect childRect = IconDelegate::getChildArrowRect(containingRect);
    if(childRect.contains(pos)){
        listWidgetItem->setSelected(true);
        setCurrentRow(index.row());
        CatItem clickItem(addPrefix(OPERATION_PREFIX,GOTO_CHILD_OPERATION));
        gMainWidget->operateOnItem(path,clickItem);
        return;
    }

    QRect depRect = IconDelegate::getDepricateItemRect(containingRect);
    if(depRect.contains(localPos)){
        CatItem depricateItem(addPrefix(OPERATION_PREFIX,DEPRICATE_OPERATION_NAME));
        //emit listItemAction(path, depricateItem);
        //fickin signals not going through...
        gMainWidget->operateOnItem(path,depricateItem);
        return;
    }
    if(listWidgetItem){
        listWidgetItem->setSelected(true);
        setCurrentRow(index.row());
        CatItem clickItem(addPrefix(OPERATION_PREFIX,SELECTION_OPERATION_NAME));
        gMainWidget->operateOnItem(path,clickItem);
    }

}
Example #3
0
void GraphicsScene::
        drawBackground(QPainter *painter, const QRectF & rectf)
{
    if (!painter->device())
        return;

    double T = last_frame_.elapsedAndRestart();
    TIME_PAINTGL TaskTimer tt("GraphicsScene: Draw, last frame %.0f ms / %.0f fps", T*1e3, 1/T);
    if (update_timer_->isActive ())
        TaskInfo("GraphicsScene: Forced redraw");

    painter->beginNativePainting();

    try { {
        GlException_CHECK_ERROR();
        renderview_->initializeGL();

        float dpr = painter->device ()->devicePixelRatio();
        renderview_->model->render_settings.dpifactor = dpr;
        unsigned w = painter->device()->width();
        unsigned h = painter->device()->height();
        w *= dpr;
        h *= dpr;

        renderview_->setStates();

        {
            TIME_PAINTGL_DETAILS TaskTimer tt("glClear");
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        }

        QRect rect = QRectF(rectf.topLeft(), QSizeF(rectf.width ()-1, rectf.height ()-1)).toRect ();
        // QRect rect = tool_selector->parentTool()->geometry();
        rect.setWidth (rect.width ()*dpr);
        rect.setHeight (rect.height ()*dpr);
        rect.setLeft (rect.left ()*dpr);
        rect.setTop (rect.top ()*dpr);

        renderview_->resizeGL( rect, QSize(w,h) );

        // This changes state. Shouldn't be a part of rendering.
        renderview_->model->recompute_extent ();

        renderview_->paintGL();

        renderview_->defaultStates();
        glFlush();

        }
        GlException_CHECK_ERROR();
    } catch (const std::exception& x) {
        TaskInfo("");
        TaskInfo(boost::format("std::exception\n%s") % boost::diagnostic_information(x));
        TaskInfo("");
    } catch (...) {
        TaskInfo(boost::format("Not an std::exception\n%s") % boost::current_exception_diagnostic_information ());
    }

    painter->endNativePainting();

    if (0 < draw_more_)
        draw_more_--;
    if (0 < draw_more_)
        update_timer_->start(5);
}
void QcMultiSlider::paintEvent( QPaintEvent *e )
{
  using namespace QtCollider::Style;
  using QtCollider::Style::Ellipse;
  using QtCollider::Style::RoundRect;

  Q_UNUSED(e);
  QPainter p(this);
  p.setRenderHint( QPainter::Antialiasing, true );

  RoundRect frame(rect(), 2);
  drawSunken( &p, palette(), frame, background(), hasFocus() ? focusColor() : QColor() );

  if( !_values.count() ) return;

  p.setRenderHint( QPainter::Antialiasing, false );

  bool horiz = ort == Qt::Horizontal;

  QRect bounds( contentsRect() );

  p.setClipRect( bounds );

  if( horiz ) {
    p.translate( bounds.topLeft() );
    p.rotate(90);
    p.scale(1.0, -1.0);
    bounds.setSize( QSize( bounds.height(), bounds.width() ) );
  }
  else {
    p.translate( bounds.left(), bounds.top() + bounds.height() );
    p.scale(1.0, -1.0);
  }

  int count = _values.count() - startIndex;
  qreal spacing, width, yscale;

  spacing = elastic ? (qreal) bounds.width() / count : thumbSize.width() + gap;
  width = elastic ? qMin( spacing, (qreal) thumbSize.width() ) : thumbSize.width();
  yscale = bounds.height();
  if( !isFilled ) yscale -= thumbSize.height();

  const QColor & fillClr = fillColor();

  // selection

  if( highlight ) {
    int i = _currentIndex - startIndex;
    int c = qMin( count - i, _selectionSize );
    if(c) {
      QRect r;
      r.setHeight( bounds.height() );
      r.setWidth( c * spacing );
      r.moveLeft( i * spacing );

      QColor hlColor = fillClr;
      hlColor.setAlpha( 70 );
      p.fillRect( r, hlColor );
    }
  }

  QPen pen;
  pen.setColor(strokeColor());
  pen.setWidth(0);
  p.setPen(pen);

  // lines

  if( drawLines ) {
    bool fill = isFilled & !drawRects;

    p.save();

    p.setRenderHint( QPainter::Antialiasing, true );
    p.translate( spacing * 0.5, isFilled ? 0.0 : thumbSize.height() * 0.5 );
    p.scale( 1.0, (qreal) yscale );
    if( fill ) p.setBrush( fillClr );

    QPainterPath path;

    // value line

    path.moveTo( 0, _values[startIndex] );
    for( int i = 1; i < count; ++i )
      path.lineTo( (qreal) i * spacing, _values[i + startIndex] );

    // reference line

    int refcount = _ref.count() - startIndex;
    if( refcount > 0 || fill ) {
      qreal x, y;
      int i = count - 1;

      x = i * spacing;
      y = i < refcount ? _ref[i + startIndex] : 0.f;
      if( fill ) path.lineTo(x, y);
      else path.moveTo(x, y);

      while( --i >= 0 ) {
        x = i * spacing;
        y = i < refcount ? _ref[i + startIndex] : 0.f;
        path.lineTo(x, y);
      }

      if( fill ) path.closeSubpath();
    }

    p.drawPath( path );

    p.restore();
  }

  // rects

  if( drawRects ) {
    p.setRenderHint( QPainter::Antialiasing, false );
    p.translate( (spacing - width) * 0.5, 0 );
    p.setBrush( fillClr );

    QRectF r;
    r.setWidth( width );

    if( isFilled ) {
      int refcount = _ref.count() - startIndex;
      for( int i = 0; i < count; ++i ) {
        int ref = (i < refcount ? _ref[i + startIndex] : 0.f) * yscale;
        int val = _values[i + startIndex] * yscale;
        r.moveLeft( i * spacing );
        r.moveTop( ref );
        r.setHeight( val - ref );
        if(horiz) p.drawRect(r.normalized().adjusted(0,0,-1,-1));
        else p.drawRect(r.normalized().adjusted(0,1,-1,0));
      }
    }
    else {
      r.setHeight( thumbSize.height() );
      for( int i = 0; i < count; ++i ) {
        r.moveLeft( i * spacing );
        r.moveTop( _values[i + startIndex] * yscale );
        if(horiz) p.drawRect(r.adjusted(0,0,-1,-1));
        else p.drawRect(r.adjusted(0,1,-1,0));
      }
    }
  }
}
void KateArgumentHintTree::updateGeometry(QRect geom) {
  //Avoid recursive calls of updateGeometry
  static bool updatingGeometry = false;
  if( updatingGeometry ) return;
  updatingGeometry = true;

  if( model()->rowCount(QModelIndex()) == 0 ) {
/*  kDebug( 13035 ) << "KateArgumentHintTree:: empty model";*/
    hide();
    setGeometry(geom);
    updatingGeometry = false;
    return;
  }

  int bottom = geom.bottom();
  int totalWidth = resizeColumns();
  int totalHeight = 0;
  for(int a = 0; a < model()->rowCount( QModelIndex() ); ++a) {
    QModelIndex index(model()->index(a, 0));
    totalHeight += rowHeight(index);
    for(int b = 0; b < model()->rowCount(index); ++b) {
      QModelIndex childIndex = index.child(b, 0);
      totalHeight += rowHeight(childIndex);
    }
  }

  totalHeight += frameWidth()*2;

  QRect topRect = visualRect(model()->index(0, 0));
  QRect contentRect = visualRect(model()->index(model()->rowCount(QModelIndex())-1, 0));

  geom.setHeight(totalHeight);

  geom.moveBottom(bottom);
//   if( totalWidth > geom.width() )
    geom.setWidth(totalWidth);

  bool enableScrollBars = false;

  //Resize and move so it fits the screen horizontally
  int maxWidth = (QApplication::desktop()->screenGeometry(m_parent->view()).width()*3)/4;
  if( geom.width() > maxWidth ) {
    geom.setWidth(maxWidth);
    geom.setHeight(geom.height() + horizontalScrollBar()->height() +2);
    geom.moveBottom(bottom);
    enableScrollBars = true;
  }

  if (geom.right() > QApplication::desktop()->screenGeometry(m_parent->view()).right())
    geom.moveRight( QApplication::desktop()->screenGeometry(m_parent->view()).right() );

  if( geom.left() < QApplication::desktop()->screenGeometry(m_parent->view()).left() )
    geom.moveLeft(QApplication::desktop()->screenGeometry(m_parent->view()).left());

  //Resize and move so it fits the screen vertically
  bool resized = false;
  if( geom.top() < QApplication::desktop()->screenGeometry(this).top() ) {
    int offset = QApplication::desktop()->screenGeometry(this).top() - geom.top();
    geom.setBottom( geom.bottom() - offset );
    geom.moveTo(geom.left(), QApplication::desktop()->screenGeometry(this).top());
    resized = true;
  }

  if(geom != geometry())
  {
    setUpdatesEnabled(false);
    setAnimated(false);

    setHorizontalScrollBarPolicy( enableScrollBars ? Qt::ScrollBarAlwaysOn : Qt::ScrollBarAlwaysOff );

  /*  kDebug( 13035 ) << "KateArgumentHintTree::updateGeometry: updating geometry to " << geom;*/
    setGeometry(geom);

    if( resized && currentIndex().isValid() )
      scrollTo(currentIndex());

    setUpdatesEnabled(true);
  }

  updatingGeometry = false;
}
Example #6
0
	void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index, GCUserViewItem* item) const
	{
		mp->save();
		QStyleOptionViewItem o = option;
		QPalette palette = o.palette;
		MUCItem::Role r = item->s.mucItem().role();
		QRect rect = o.rect;

		if(nickColoring_) {
			if(r == MUCItem::Moderator)
				palette.setColor(QPalette::Text, colorModerator_);
			else if(r == MUCItem::Participant)
				palette.setColor(QPalette::Text, colorParticipant_);
			else if(r == MUCItem::Visitor)
				palette.setColor(QPalette::Text, colorVisitor_);
			else
				palette.setColor(QPalette::Text, colorNoRole_);
		}

		mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base));

		if(showAvatar_) {
			QPixmap ava = item->avatar();
			if(ava.isNull()) {
				ava = IconsetFactory::iconPixmap("psi/default_avatar");
			}
			ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_);
			QRect avaRect(rect);
			avaRect.setWidth(ava.width());
			avaRect.setHeight(ava.height());
			if(!avatarAtLeft_) {
				avaRect.moveTopRight(rect.topRight());
				avaRect.translate(-1, 1);
				rect.setRight(avaRect.left() - 1);
			}
			else {
				avaRect.translate(1, 1);
				rect.setLeft(avaRect.right() + 1);
			}
			mp->drawPixmap(avaRect, ava);
		}

		QPixmap status = showStatusIcons_ ? item->icon() : QPixmap();
		int h = rect.height();
		int sh = status.isNull() ? 0 : status.height();
		rect.setHeight(qMax(sh, fontHeight_));
		rect.moveTop(rect.top() + (h - rect.height())/2);
		if(!status.isNull()) {
			QRect statusRect(rect);
			statusRect.setWidth(status.width());
			statusRect.setHeight(status.height());
			statusRect.translate(1, 1);
			mp->drawPixmap(statusRect, status);
			rect.setLeft(statusRect.right() + 2);
		}
		else
			rect.setLeft(rect.left() + 2);

		mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text)));
		mp->setFont(o.font);
		mp->setClipRect(rect);
		QTextOption to;
		to.setWrapMode(QTextOption::NoWrap);
		mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to);

		QList<QPixmap> rightPixs;
		if(showClients_) {
			GCUserView *gcuv = (GCUserView*)item->treeWidget();
			GCMainDlg* dlg = gcuv->mainDlg();
			QPixmap clientPix;
			if(dlg) {
				UserListItem u;
				const QString &nick = item->text(0);
				Jid caps_jid(/*s.mucItem().jid().isEmpty() ? */ dlg->jid().withResource(nick) /* : s.mucItem().jid()*/);
				QString client_name = dlg->account()->capsManager()->clientName(caps_jid);
				QString client_version = (client_name.isEmpty() ? QString() : dlg->account()->capsManager()->clientVersion(caps_jid));
				UserResource ur;
				ur.setClient(client_name,client_version,"");
				u.userResourceList().append(ur);
				QStringList clients = u.clients();
				if(!clients.isEmpty())
					clientPix = IconsetFactory::iconPixmap("clients/" + clients.takeFirst());
			}
			if(!clientPix.isNull())
				rightPixs.push_back(clientPix);
		}

		if(showAffiliations_) {
			MUCItem::Affiliation a = item->s.mucItem().affiliation();
			QPixmap pix;
			if(a == MUCItem::Owner)
				pix = IconsetFactory::iconPixmap("affiliation/owner");
			else if(a == MUCItem::Admin)
				pix = IconsetFactory::iconPixmap("affiliation/admin");
			else if(a == MUCItem::Member)
				pix = IconsetFactory::iconPixmap("affiliation/member");
			else if(a == MUCItem::Outcast)
				pix = IconsetFactory::iconPixmap("affiliation/outcast");
			else
				pix = IconsetFactory::iconPixmap("affiliation/noaffiliation");
			if(!pix.isNull())
				rightPixs.push_back(pix);
		}

		mp->restore();

		if(rightPixs.isEmpty())
			return;

		int sumWidth = 0;
		foreach (const QPixmap& pix, rightPixs) {
				sumWidth += pix.width();
		}
		sumWidth += rightPixs.count();

		QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base);
		QColor tbgc = bgc;
		tbgc.setAlpha(0);
		QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0);
		grad.setColorAt(0, tbgc);
		grad.setColorAt(1, bgc);
		QBrush tbakBr(grad);
		QRect gradRect(rect);
		gradRect.setLeft(gradRect.right() - sumWidth - 20);
		mp->fillRect(gradRect, tbakBr);

		QRect iconRect(rect);
		for (int i=0; i<rightPixs.size(); i++) {
			const QPixmap pix = rightPixs[i];
			iconRect.setRight(iconRect.right() - pix.width() -1);
			mp->drawPixmap(iconRect.topRight(), pix);
		}

	}
Example #7
0
void UcClassCanvas::draw(QPainter & p) {
  if (! visible()) return;
  p.setRenderHint(QPainter::Antialiasing, true);
  QRect r = rect();
  QFontMetrics fm(the_canvas()->get_font(UmlNormalFont));
  QFontMetrics fim(the_canvas()->get_font(UmlNormalItalicFont));
  QColor bckgrnd = p.backgroundColor();
  double zoom = the_canvas()->zoom();
  FILE * fp = svg();

  if (fp != 0)
    fputs("<g>\n", fp);

  p.setBackgroundMode((used_color == UmlTransparent) ? ::Qt::TransparentMode : ::Qt::OpaqueMode);

  QColor co = color(used_color);
  
  if (used_view_mode == asClass) {
    if (used_color != UmlTransparent) {
      const int shadow = the_canvas()->shadow();

      if (shadow != 0) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
	
	p.fillRect (r.right(), r.top() + shadow,
		    shadow, r.height() - 1,
		    ::Qt::darkGray);
	p.fillRect (r.left() + shadow, r.bottom(),
		    r.width() - 1, shadow,
		    ::Qt::darkGray);

	if (fp != 0) {
	  fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		  " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		  QColor(::Qt::darkGray).rgb()&0xffffff,
		  r.right(), r.top() + shadow, shadow - 1, r.height() - 1 - 1);

	  fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		  " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		  QColor(::Qt::darkGray).rgb()&0xffffff,
		  r.left() + shadow, r.bottom(), r.width() - 1 - 1, shadow - 1);
	}
      }
    }
    
    p.setBackgroundColor(co);
  
    if (used_color != UmlTransparent) {
      p.fillRect(r, co);

      if (fp != 0)
	fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		svg_color(used_color), 
		r.x(), r.y(), r.width() - 1, r.height() - 1);
    }
    else if (fp != 0)
      fprintf(fp, "\t<rect fill=\"none\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
	      r.x(), r.y(), r.width() - 1, r.height() - 1);

    p.drawRect(r);
  }
  
  const ClassData * data = ((ClassData *) browser_node->get_data());
  const int two = (int) (2 * zoom);
  int he = fm.height() + two;
  
  if (data->get_n_formalparams() != 0)
    r.setTop(r.top() + fm.height());
  
  switch (used_view_mode) {
  case asInterface:
    draw_interface_icon(p, r, used_color, zoom);
    r.setTop(r.top() + (int) (INTERFACE_SIZE * zoom) + two);
    break;
  case asControl:
    draw_control_icon(p, r, used_color, zoom);
    r.setTop(r.top() + (int) (CONTROL_HEIGHT * zoom) + two);
    break;
  case asBoundary:
    draw_boundary_icon(p, r, used_color, zoom);
    r.setTop(r.top() + (int) (BOUNDARY_HEIGHT * zoom) + two);
    break;
  case asEntity:
    draw_entity_icon(p, r, used_color, zoom);
    r.setTop(r.top() + (int) (ENTITY_SIZE * zoom) + two);
    break;
  case asActor:
    {
      QRect ra = r;
      
      ra.setHeight((int) (ACTOR_SIZE * zoom));
      ra.setLeft(ra.left() + 
		 (int) ((ra.width() - ACTOR_SIZE * zoom)/2));
      ra.setWidth(ra.height());
      draw_actor(&p, ra);
    }
    r.setTop(r.top() + (int) (ACTOR_SIZE * zoom) + two);
    break;
  case Natural:
    {
      const QPixmap * px = 
	ProfiledStereotypes::diagramPixmap(data->get_stereotype(), zoom);
      int lft = (px->width() < width()) ? r.x() + (width() - px->width())/2 : r.x();

      p.drawPixmap(lft, r.y(), *px);
      if (fp != 0)
	// pixmap not really exported in SVG
	fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-width=\"1\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" />\n",
		svg_color(UmlBlack), lft, r.y(), px->width() - 1, px->height() - 1);

      r.setTop(r.top() + px->height());
    }
    break;
  default:	// class
    r.setTop(r.top() + two);
    if (data->get_stereotype()[0]) {
      p.setFont(the_canvas()->get_font(UmlNormalFont));
      p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop, 
		 QString("<<") + toUnicode(data->get_short_stereotype()) + ">>");
      if (fp != 0)
	draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop, 
		  QString("<<") + toUnicode(data->get_short_stereotype()) + ">>",
		  p.font(), fp);
      r.setTop(r.top() + he + two);
    }
  }
  
  p.setBackgroundMode(::Qt::TransparentMode);
  p.setFont((data->get_is_abstract())
	    ? the_canvas()->get_font(UmlNormalItalicFont)
	    : the_canvas()->get_font(UmlNormalFont));
  p.drawText(r, ::Qt::AlignHCenter + ::Qt::AlignTop, full_name);
  if (fp != 0)
    draw_text(r, ::Qt::AlignHCenter + ::Qt::AlignTop, full_name, p.font(), fp);

  p.setFont(the_canvas()->get_font(UmlNormalFont));
  
  if (used_view_mode == asClass) {
    r.setTop(r.top() + he);
    p.drawLine(r.topLeft(), r.topRight());
    
    if (fp != 0)
      fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
	      " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
	      r.left(), r.top(), r.right(), r.top());
    
    r.setTop(r.top() + (int) (8 * zoom));
    p.drawLine(r.topLeft(), r.topRight());
    
    if (fp != 0)
      fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
	      " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
	      r.left(), r.top(), r.right(), r.top());
  }
  
  if (fp != 0)
    fputs("</g>\n", fp);
    
  p.setBackgroundColor(bckgrnd);
  
  if (selected())
    show_mark(p, rect());
}
Example #8
0
/*
 * If minsize and multiline are defined, minimize the width by using
 * as many lines as possible.
 */
bool MythUIText::MakeNarrow(QRect &min_rect)
{
    QFontMetrics fm(GetFontProperties()->face());

    if (m_scrolling || !m_MultiLine)
    {
        min_rect = fm.boundingRect(m_Area, m_Justification, m_CutMessage);
        return false;
    }

    /*
     * Shrinkage is desired, and multiline is allowed
     * If more than one line will fit, squeeze to the left
     */
    if ((m_Area.height() + fm.leading()) / fm.lineSpacing() < 2)
    {
        min_rect = fm.boundingRect(m_Area, m_Justification, m_CutMessage);
        return false;
    }

    // Give plenty of vertical space, to prevent clipping from coloring results
    min_rect = m_Area;
    min_rect.setHeight(m_Area.height() * 2);

    QRect rect;
    int   first = 1;
    int   last  = m_CutMessage.size() - 2;
    int   min_width = INT_MAX;

    /*
     * Test from each end to find the best width to use.
     * An interior line may actually represent the best width, but it
     * is not worth the extra complexity to test interior lines.
     */
    while (first < last && min_width > m_MinSize.x())
    {
        if ((first = m_CutMessage.indexOf(' ', first)) < 1)
            break;

        min_rect.setWidth(fm.width(m_CutMessage.left(first)));

        if (min_rect.width() < m_Area.width())
        {
            rect = fm.boundingRect(min_rect, m_Justification, m_CutMessage);
            if (rect.height() <= m_Area.height() && rect.width() < min_width)
                min_width = rect.width();
        }

        if ((last = m_CutMessage.lastIndexOf(' ', last)) < 0)
            break;

        min_rect.setWidth(fm.width(m_CutMessage.mid(last)));

        if (min_rect.width() < m_Area.width())
        {
            rect = fm.boundingRect(min_rect, m_Justification, m_CutMessage);
            if (rect.height() <= m_Area.height() && rect.width() < min_width)
                min_width = rect.width();
        }

        ++first;
        --last;
    }

    if (min_width == INT_MAX)
    {
        // won't fit, even when the ara is the maxium size
        min_rect = fm.boundingRect(m_Area, m_Justification, m_CutMessage);
        return false;
    }
    else
    {
        if (min_width < m_MinSize.x() - m_Area.x())
            min_width = m_MinSize.x() - m_Area.x();

        // Found the minimal width which will accommodate the whole message.
        min_rect.setHeight(m_Area.height());
        min_rect.setWidth(min_width);
        min_rect = fm.boundingRect(min_rect, m_Justification, m_CutMessage);
        return true;
    }
}
Example #9
0
void CircuitsWidget::mouseReleaseEvent(QMouseEvent *event) {
	setFocus();
	if(connectingComponent){
		// resetting cursor
		QCursor c;
		c.setShape(Qt::ArrowCursor);
		setCursor(c);
		// checking click on components
		QPoint click = event->pos();
		for(int it = 0; it < componentList.size(); it++){
			QRect r = componentList[it]->rect();
			r.setX(componentList[it]->x());
			r.setY(componentList[it]->y());
			r.setWidth(componentList[it]->width());
			r.setHeight(componentList[it]->height());
			bool c1 = r.contains(click); // the mouserelease is on a component
			bool c2 = !(componentOnConnection == componentList[it]); // not the same component
			bool c3 = (componentOnConnection->outComponentList.indexOf(componentList[it])==-1); // not already connected
			bool c4 = componentOnConnection->getComponentType() != 2; // the left component is not a collector
			bool c5 = componentList[it]->getComponentType() != 3; // the right component is not a variable
            // if the right component is a collector it must be unconnected
            bool c6;
            if(componentList[it]->getComponentType() == 2)
                c6 = componentList[it]->inComponentList.isEmpty();
            else
                c6 = true;  
            // if the right component is a NOT port it must be unconnected
            bool c7;
            if(componentList[it]->getComponentType() == 6)
                c7 = componentList[it]->inComponentList.isEmpty();
            else
                c7 = true;
            // if the right component is a divider, it must be unconnected
            bool c8;
            if(componentList[it]->getComponentType() == 7)
                c8 = componentList[it]->inComponentList.isEmpty();
            else
                c8 = true;
			if(c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8){
				// creating and set new wire
				Wire *w = new Wire(componentOnConnection, componentList[it]);
				wireList.append(w);
				// setting connections
				componentOnConnection->outComponentList.append(componentList[it]);
				componentList[it]->inComponentList.append(componentOnConnection);
				// value injection
				int ctype = componentList[it]->getComponentType();
				switch(ctype){
                    case(8):{
                        // muler
                        int tmp = componentList[it]->getValue();
                        componentList[it]->setValue(tmp * componentOnConnection->getValue());
                        break;
                    }
                    case(7):{
                        // diver
                        Diver* d = (Diver*) componentList[it].data(); // pay attenction
                        int r = componentOnConnection->getValue() / d->getDivider();
                        componentList[it]->setValue(r);
                        break;
                    }
                    case(6):{
                        //noter
                        if(componentOnConnection->getValue() != 0)
                            componentList[it]->setValue(0);
                        else
                            componentList[it]->setValue(1);
                        break;
                    }
                    case(5):{
                        //orer
                        bool tmp = componentList[it]->getValue();
                        componentList[it]->setValue(tmp || componentOnConnection->getValue());
                        break;
                    }
                    case(4):{
                        //ander
                        bool tmp = componentList[it]->getValue();
                        componentList[it]->setValue(tmp && componentOnConnection->getValue());
                        break;
                    }
					case(3):{
						//variabile
						printf("WARNING: This component shouldn't have any incoming component\n");
						break;
					}
					case(2):{
						// collector
						componentList[it]->setValue(componentOnConnection->getValue());
						break;
					}
					case(1):{
						//adder
						int tmp = componentList[it]->getValue();
						componentList[it]->setValue(tmp + componentOnConnection->getValue());
						break;
					}
					default:{
						printf("FATAL ERROR: invalid component type\n");
						exit(1);
					}
				}
				repaint();
			}
		}
		connectingComponent = false;
		componentOnConnection = NULL;
	}
}
Example #10
0
    void paintContact(QPainter* mp, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        mp->save();
        QStyleOptionViewItem o = option;
        QPalette palette = o.palette;
        MUCItem::Role r = index.data(GCUserModel::StatusRole).value<Status>().mucItem().role();
        QRect rect = o.rect;

        if(nickColoring_) {
            if(r == MUCItem::Moderator)
                palette.setColor(QPalette::Text, colorModerator_);
            else if(r == MUCItem::Participant)
                palette.setColor(QPalette::Text, colorParticipant_);
            else if(r == MUCItem::Visitor)
                palette.setColor(QPalette::Text, colorVisitor_);
            else
                palette.setColor(QPalette::Text, colorNoRole_);
        }

        mp->fillRect(rect, (o.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base));

        if(showAvatar_) {
            QPixmap ava = index.data(GCUserModel::AvatarRole).value<QPixmap>();
            if(ava.isNull()) {
                ava = IconsetFactory::iconPixmap("psi/default_avatar");
            }
            ava = AvatarFactory::roundedAvatar(ava, avatarRadius_, avatarSize_);
            QRect avaRect(rect);
            avaRect.setWidth(ava.width());
            avaRect.setHeight(ava.height());
            if(!avatarAtLeft_) {
                avaRect.moveTopRight(rect.topRight());
                avaRect.translate(-1, 1);
                rect.setRight(avaRect.left() - 1);
            }
            else {
                avaRect.translate(1, 1);
                rect.setLeft(avaRect.right() + 1);
            }
            mp->drawPixmap(avaRect, ava);
        }

        QPixmap status = showStatusIcons_? PsiIconset::instance()->status(index.data(GCUserModel::StatusRole).value<Status>()).pixmap() : QPixmap();
        int h = rect.height();
        int sh = status.isNull() ? 0 : status.height();
        rect.setHeight(qMax(sh, fontHeight_));
        rect.moveTop(rect.top() + (h - rect.height())/2);
        if(!status.isNull()) {
            QRect statusRect(rect);
            statusRect.setWidth(status.width());
            statusRect.setHeight(status.height());
            statusRect.translate(1, 1);
            mp->drawPixmap(statusRect, status);
            rect.setLeft(statusRect.right() + 2);
        }
        else
            rect.setLeft(rect.left() + 2);

        mp->setPen(QPen((o.state & QStyle::State_Selected) ? palette.color(QPalette::HighlightedText) : palette.color(QPalette::Text)));
        mp->setFont(o.font);
        mp->setClipRect(rect);
        QTextOption to;
        to.setWrapMode(QTextOption::NoWrap);
        mp->drawText(rect, index.data(Qt::DisplayRole).toString(), to);

        QList<QPixmap> rightPixs;

        if(showAffiliations_) {
            QPixmap pix = index.data(GCUserModel::AffilationIconRole).value<QPixmap>();;
            if(!pix.isNull())
                rightPixs.push_back(pix);
        }

        if(showClients_) {
            QPixmap clientPix = index.data(GCUserModel::ClientIconRole).value<QPixmap>();
            if(!clientPix.isNull())
                rightPixs.push_back(clientPix);
        }

        mp->restore();

        if(rightPixs.isEmpty())
            return;

        int sumWidth = 0;
        foreach (const QPixmap& pix, rightPixs) {
                sumWidth += pix.width();
        }
        sumWidth += rightPixs.count();

        QColor bgc = (option.state & QStyle::State_Selected) ? palette.color(QPalette::Highlight) : palette.color(QPalette::Base);
        QColor tbgc = bgc;
        tbgc.setAlpha(0);
        QLinearGradient grad(rect.right() - sumWidth - 20, 0, rect.right() - sumWidth, 0);
        grad.setColorAt(0, tbgc);
        grad.setColorAt(1, bgc);
        QBrush tbakBr(grad);
        QRect gradRect(rect);
        gradRect.setLeft(gradRect.right() - sumWidth - 20);
        mp->fillRect(gradRect, tbakBr);

        QRect iconRect(rect);
        for (int i=0; i<rightPixs.size(); i++) {
            const QPixmap pix = rightPixs[i];
            iconRect.setRight(iconRect.right() - pix.width() -1);
            mp->drawPixmap(iconRect.topRight(), pix);
        }

    }
Example #11
0
QPoint popupPosition(KPanelApplet::Direction d,
                     const QWidget* popup,
                     const QWidget* source,
                     const QPoint& offset)
{
    QRect r;
    if (source->isTopLevel())
    {
        r = source->geometry();
    }
    else
    {
        r = QRect(source->mapToGlobal(QPoint(0, 0)),
                  source->mapToGlobal(QPoint(source->width(), source->height())));

        switch (d)
        {
            case KPanelApplet::Left:
            case KPanelApplet::Right:
                r.setLeft( source->topLevelWidget()->x() );
                r.setWidth( source->topLevelWidget()->width() );
                break;
            case KPanelApplet::Up:
            case KPanelApplet::Down:
                r.setTop( source->topLevelWidget()->y() );
                r.setHeight( source->topLevelWidget()->height() );
                break;
        }
    }

    switch (d)
    {
        case KPanelApplet::Left:
        case KPanelApplet::Right:
        {
            QDesktopWidget* desktop = QApplication::desktop();
            QRect screen = desktop->screenGeometry(desktop->screenNumber(const_cast<QWidget*>(source)));
            int x = (d == KPanelApplet::Left) ? r.left() - popup->width() :
                                                r.right() + 1;
            int y = r.top() + offset.y();

            // try to keep this on screen
            if (y + popup->height() > screen.bottom())
            {
                y = r.bottom() - popup->height() + offset.y();

                if (y < screen.top())
                {
                    y = screen.bottom() - popup->height();

                    if (y < screen.top())
                    {
                        y = screen.top();
                    }
                }
            }

            return QPoint(x, y);
        }
        case KPanelApplet::Up:
        case KPanelApplet::Down:
        default:
        {
            int x = 0;
            int y = (d == KPanelApplet::Up) ? r.top() - popup->height() :
                                              r.bottom() + 1;

            if (QApplication::reverseLayout())
            {
                x = r.right() - popup->width() + 1;

                if (offset.x() > 0)
                {
                    x -= r.width() - offset.x();
                }

                // try to keep this on the screen
                if (x - popup->width() < 0)
                {
                    x = r.left();
                }

                return QPoint(x, y);
            }
            else
            {
                QDesktopWidget* desktop = QApplication::desktop();
                QRect screen = desktop->screenGeometry(desktop->screenNumber(const_cast<QWidget*>(source)));
                x = r.left() + offset.x();

                // try to keep this on the screen
                if (x + popup->width() > screen.right())
                {
                    x = r.right() - popup->width() + 1 + offset.x();

                    if (x < screen.left())
                    {
                        x = screen.left();
                    }
                }
            }

            return QPoint(x, y);
        }
    }
}
Example #12
0
/**
   Take data from image, draw text at x|y with specified parameters.
   If destPainter is null, draw to image,
   if destPainter is not null, draw directly using the painter.
   Returns modified area of image.
*/
QRect InsertTextWidget::composeImage(DImg* const image, QPainter* const destPainter,
                                     int x, int y,
                                     QFont font, float pointSize, int textRotation, QColor textColor,
                                     int textOpacity, int alignMode, const QString& textString,
                                     bool transparentBackground, QColor backgroundColor,
                                     BorderMode borderMode, int borderWidth, int spacing, float fontScale)
{
    /*
        The problem we have to solve is that we have no pixel access to font rendering,
        we have to let Qt do the drawing. On the other hand we need to support 16 bit, which
        cannot be done with QPixmap.
        The current solution cuts out the text area, lets Qt do its drawing, converts back and blits to original.
    */

    int maxWidth, maxHeight;

    if (x == -1 && y == -1)
    {
        maxWidth  = image->width();
        maxHeight = image->height();
    }
    else
    {
        maxWidth  = image->width()  - x;
        maxHeight = image->height() - y;
    }

    fontScale = qMax(0.01f, fontScale);

    // find out size of the area that we are drawing to
    font.setPointSizeF(pointSize);
    QFontMetrics fontMt(font);
    QRect fontRect = fontMt.boundingRect(0, 0,
                                         qRound(maxWidth  / fontScale),
                                         qRound(maxHeight / fontScale),
                                         alignMode, textString);

    fontRect.setWidth(qRound(fontRect.width()   * fontScale));
    fontRect.setHeight(qRound(fontRect.height() * fontScale));

    if (!fontRect.isValid())
    {
        return QRect();
    }

    int fontWidth, fontHeight;

    switch (textRotation)
    {
        case ROTATION_NONE:
        case ROTATION_180:
        default:
            fontWidth = fontRect.width();
            fontHeight = fontRect.height();
            break;

        case ROTATION_90:
        case ROTATION_270:
            fontWidth = fontRect.height();
            fontHeight = fontRect.width();
            break;
    }

    // x, y == -1 means that we have to find a good initial position for the text here
    if (x == -1 && y == -1)
    {
        int boxWidth  = fontWidth  + 2 * borderWidth + 2 * spacing;
        int boxHeight = fontHeight + 2 * borderWidth + 2 * spacing;

        // was a valid position hint stored from last use?
        if (d->positionHint.isValid())
        {
            // We assume that people tend to orient text along the edges,
            // so we do some guessing so that positions such as "in the lower right corner"
            // will be remembered across different image sizes.

            // get relative positions
            float fromTop    =       (float)d->positionHint.top()    / 10000.0;
            float fromBottom = 1.0 - (float)d->positionHint.bottom() / 10000.0;
            float fromLeft   =       (float)d->positionHint.left()   / 10000.0;
            float fromRight  = 1.0 - (float)d->positionHint.right()  / 10000.0;

            // calculate horizontal position
            if (fromLeft < fromRight)
            {
                x = qRound(fromLeft * maxWidth);

                // we are placing from the smaller distance,
                // so if now the larger distance is actually too small,
                // fall back to standard placement, nothing to lose.
                if (x + boxWidth > maxWidth)
                {
                    x = qMax( (maxWidth - boxWidth) / 2, 0);
                }
            }
            else
            {
                x = maxWidth - qRound(fromRight * maxWidth) - boxWidth;

                if ( x < 0 )
                {
                    x = qMax( (maxWidth - boxWidth) / 2, 0);
                }
            }

            // calculate vertical position
            if (fromTop < fromBottom)
            {
                y = qRound(fromTop * maxHeight);

                if (y + boxHeight > maxHeight)
                {
                    y = qMax( (maxHeight - boxHeight) / 2, 0);
                }
            }
            else
            {
                y = maxHeight - qRound(fromBottom * maxHeight) - boxHeight;

                if ( y < 0 )
                {
                    y = qMax( (maxHeight - boxHeight) / 2, 0);
                }
            }

            if (! QRect(x, y, boxWidth, boxHeight).
                intersects(QRect(0, 0, maxWidth, maxHeight)) )
            {
                // emergency fallback - nothing is visible
                x = qMax( (maxWidth - boxWidth)   / 2, 0);
                y = qMax( (maxHeight - boxHeight) / 2, 0);
            }

            // invalidate position hint, use only once
            d->positionHint = QRect();
        }
        else
        {
            // use standard position
            x = qMax( (maxWidth - boxWidth)   / 2, 0);
            y = qMax( (maxHeight - boxHeight) / 2, 0);
        }
    }

    // create a rectangle relative to image
    QRect drawRect( x, y, fontWidth + 2 * borderWidth + 2 * spacing, fontHeight + 2 * borderWidth  + 2 * spacing);

    // create a rectangle relative to textArea, excluding the border
    QRect textAreaBackgroundRect( borderWidth, borderWidth, fontWidth + 2 * spacing, fontHeight + 2 * spacing);

    // create a rectangle relative to textArea, excluding the border and spacing
    QRect textAreaTextRect( borderWidth + spacing, borderWidth + spacing, fontWidth, fontHeight );

    // create a rectangle relative to textArea, including the border,
    // for drawing the rectangle, taking into account that the width of the QPen goes in and out in equal parts
    QRect textAreaDrawRect( borderWidth / 2, borderWidth / 2, fontWidth + borderWidth + 2 * spacing,
                            fontHeight + borderWidth + 2 * spacing );

    // cut out the text area
    DImg textArea = image->copy(drawRect);

    if (textArea.isNull())
    {
        return QRect();
    }

    // compose semi-transparent background over textArea
    DColorComposer* composer = DColorComposer::getComposer(DColorComposer::PorterDuffNone);

    if (transparentBackground)
    {
        DImg transparentLayer(textAreaBackgroundRect.width(), textAreaBackgroundRect.height(), textArea.sixteenBit(), true);
        DColor transparent(backgroundColor);
        transparent.setAlpha(d->transparency);

        if (image->sixteenBit())
        {
            transparent.convertToSixteenBit();
        }

        transparentLayer.fill(transparent);
        textArea.bitBlendImage(composer, &transparentLayer, 0, 0, transparentLayer.width(), transparentLayer.height(),
                               textAreaBackgroundRect.x(), textAreaBackgroundRect.y());
    }

    DImg textNotDrawn;

    if (textArea.sixteenBit())
    {
        textNotDrawn = textArea.copy();
        textNotDrawn.convertToEightBit();
    }
    else
    {
        textNotDrawn = textArea;
    }

    // We have no direct pixel access to font rendering, so now we need to use Qt/X11 for the drawing

    // convert text area to pixmap
    QPixmap pixmap;

    if (destPainter)
    {
        // We working on tool preview, deal with CM as well
        pixmap = d->iface->convertToPixmap(textNotDrawn);
    }
    else
    {
        // We working on target image. Do no apply double CM adjustment here.
        pixmap = textNotDrawn.convertToPixmap();
    }

    int fontScaleWidth  = qRound(fontWidth  / fontScale);
    int fontScaleHeight = qRound(fontHeight / fontScale);

    QPixmap textPixmap(fontScaleWidth, fontScaleHeight);
    textPixmap.fill(Qt::transparent);

    QPainter tp(&textPixmap);
    tp.setOpacity((qreal)textOpacity / 100.0);
    tp.setPen(QPen(textColor, 1));
    tp.setFont(font);

    switch (textRotation)
    {
        case ROTATION_NONE:
            tp.drawText(0, 0, fontScaleWidth, fontScaleHeight,
                         alignMode, textString);
            break;
        case ROTATION_90:
            tp.translate(fontScaleWidth, 0);
            tp.rotate(90.0);
            tp.drawText(0, 0, fontScaleHeight, fontScaleWidth,
                        alignMode, textString);
            break;
        case ROTATION_180:
            tp.translate(fontScaleWidth, fontScaleHeight);
            tp.rotate(180.0);
            tp.drawText(0, 0, fontScaleWidth, fontScaleHeight,
                        alignMode, textString);
            break;
        case ROTATION_270:
            tp.translate(0, fontScaleHeight);
            tp.rotate(270.0);
            tp.drawText(0, 0, fontScaleHeight, fontScaleWidth,
                        alignMode, textString);
            break;
    }

    tp.end();

    // paint on pixmap
    QPainter p(&pixmap);

    p.drawPixmap(textAreaTextRect, textPixmap.scaled(fontWidth,
                                                     fontHeight,
                                                     Qt::IgnoreAspectRatio,
                                                     Qt::SmoothTransformation));
    // Drawing rectangle around text.

    if (borderMode == BORDER_NORMAL)      // Decorative border using text color.
    {
        p.setPen( QPen(textColor, borderWidth, Qt::SolidLine,
                       Qt::SquareCap, Qt::RoundJoin) ) ;
        p.drawRect(textAreaDrawRect);
    }
    else if (borderMode == BORDER_SUPPORT)  // Make simple dot line border to help user.
    {
        p.setPen(QPen(Qt::white, 1, Qt::SolidLine));
        p.drawRect(textAreaDrawRect);
        p.setPen(QPen(Qt::red, 1, Qt::DotLine));
        p.drawRect(textAreaDrawRect);
    }

    p.end();

    if (!destPainter)
    {
        // convert to QImage, then to DImg
        QImage pixmapImage = pixmap.toImage();
        DImg textDrawn(pixmapImage.width(), pixmapImage.height(), false, true, pixmapImage.bits());

        // This does not work: during the conversion, colors are altered significantly (diffs of 1 to 10 in each component),
        // so we cannot find out which pixels have actually been touched.
/*
        // Compare the result of drawing with the previous version.
        // Set all unchanged pixels to transparent
        DColor color, ncolor;
        uchar *ptr, *nptr;
        ptr = textDrawn.bits();
        nptr = textNotDrawn.bits();
        int bytesDepth = textDrawn.bytesDepth();
        int numPixels = textDrawn.width() * textDrawn.height();
        for (int i = 0; i < numPixels; ++i, ptr+= bytesDepth, nptr += bytesDepth)
        {
            color.setColor(ptr, false);
            ncolor.setColor(nptr, false);
            if ( color.red()   == ncolor.red() &&
                color.green() == ncolor.green() &&
                color.blue()  == ncolor.blue())
            {
                color.setAlpha(0);
                color.setPixel(ptr);
            }
        }
        // convert to 16 bit if needed
*/
        textDrawn.convertToDepthOfImage(&textArea);

        // now compose to original: only pixels affected by drawing text and border are changed, not whole area
        textArea.bitBlendImage(composer, &textDrawn, 0, 0, textDrawn.width(), textDrawn.height(), 0, 0);

        // copy result to original image
        image->bitBltImage(&textArea, drawRect.x(), drawRect.y());
    }
    else
    {
        destPainter->drawPixmap(drawRect.x(), drawRect.y(), pixmap, 0, 0, pixmap.width(), pixmap.height());
    }

    delete composer;

    return drawRect;
}
void PsiContactListViewDelegate::drawContact(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	drawBackground(painter, option, index);

	const QPixmap statusPixmap = this->statusPixmap(index);
	const QSize pixmapSize = statusPixmap.size();
	const QRect avatarRect = relativeRect(option, pixmapSize, QRect());
	painter->drawPixmap(avatarRect.topLeft(), statusPixmap);
	QRect r = relativeRect(option, QSize(), avatarRect, 3);

	QColor textColor;
	if(index.data(ContactListModel::IsAnimRole).toBool()) {
		if(index.data(ContactListModel::PhaseRole).toBool()) {
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status-change-animation2");
		}
		else {
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status-change-animation1");
		}
	}
	else {
		if (statusType(index) == XMPP::Status::Away || statusType(index) == XMPP::Status::XA)
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status.away");
		else if (statusType(index) == XMPP::Status::DND)
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status.do-not-disturb");
		else if (statusType(index) == XMPP::Status::Offline)
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status.offline");
		else
			textColor = ColorOpt::instance()->color("options.ui.look.colors.contactlist.status.online");
	}

	QStyleOptionViewItemV2 o = option;
	o.font = *font_;
	o.fontMetrics = *fontMetrics_;
	QPalette palette = o.palette;
	palette.setColor(QPalette::Text, textColor);
	o.palette = palette;

	QString text = nameText(o, index);
	if (showStatusMessages_ && !statusText(index).isEmpty()) {
		if(!statusSingle_) {
			text = tr("%1 (%2)").arg(text).arg(statusText(index));
			drawText(painter, o, r, text, index);
		}
		else {
			QRect txtRect(r);
			txtRect.setHeight(r.height()*2/3);
			drawText(painter, o, txtRect, text, index);
			QString statusMsg = statusText(index);
			palette.setColor(QPalette::Text, ColorOpt::instance()->color("options.ui.look.colors.contactlist.status-messages"));
			o.palette = palette;
			txtRect.moveTopRight(txtRect.bottomRight());
			txtRect.setHeight(r.height() - txtRect.height());
			o.font.setPointSize(qMax(o.font.pointSize()-2, 7));
			o.fontMetrics = QFontMetrics(o.font);
			drawText(painter, o, txtRect, statusMsg, index);
		}
	}
	else {
		if(showStatusMessages_ && statusSingle_)
			r.setHeight(r.height()*2/3);

		drawText(painter, o, r, text, index);
	}

#if 0
	int x;
	if (d->status_single)
		x = widthUsed();
	else {
		QFontMetrics fm(p->font());
		const QPixmap *pix = pixmap(column);
		x = fm.width(text(column)) + (pix ? pix->width() : 0) + 8;
	}

	if (d->u) {
		UserResourceList::ConstIterator it = d->u->priority();
		if (it != d->u->userResourceList().end()) {
			if (d->u->isSecure((*it).name())) {
				const QPixmap &pix = IconsetFactory::iconPixmap("psi/cryptoYes");
				int y = (height() - pix.height()) / 2;
				p->drawPixmap(x, y, pix);
				x += 24;
			}
		}
	}
#endif
}
void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                 const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter,option,index);

    QFont aliasFont = option.font;
    QFont subFont   = option.font;
    QFont errorFont = subFont;
    QFont progressFont = subFont;

    progressFont.setPointSize( subFont.pointSize()-2);
    //font.setPixelSize(font.weight()+);
    aliasFont.setBold(true);
    aliasFont.setPointSize( subFont.pointSize()+2 );

    QFontMetrics subFm( subFont );
    QFontMetrics aliasFm( aliasFont );
    QFontMetrics progressFm( progressFont );

    int aliasMargin = aliasFm.height()/2;
    int margin = subFm.height()/4;

    if (index.data(AddButton).toBool()) {
        QSize hint = sizeHint(option, index);
        QStyleOptionButton opt;
        static_cast<QStyleOption&>(opt) = option;
        opt.state &= ~QStyle::State_Selected;
        opt.state |= QStyle::State_Raised;
        opt.text = addFolderText();
        opt.rect.setWidth(qMin(opt.rect.width(), hint.width()));
        opt.rect.adjust(0, aliasMargin, 0, -aliasMargin);
        QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
                , option.widget
#endif
            );
        return;
    }

    if (static_cast<const FolderStatusModel *>(index.model())->classify(index) != FolderStatusModel::RootFolder) {
        return;
    }
    painter->save();

    QIcon statusIcon      = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
    QString aliasText     = qvariant_cast<QString>(index.data(HeaderRole));
    QString pathText      = qvariant_cast<QString>(index.data(FolderPathRole));
    QString remotePath    = qvariant_cast<QString>(index.data(FolderSecondPathRole));
    QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));

    int overallPercent    = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
    QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
    QString itemString    = qvariant_cast<QString>(index.data(SyncProgressItemString));
    int warningCount      = qvariant_cast<int>(index.data(WarningCount));
    bool syncOngoing      = qvariant_cast<bool>(index.data(SyncRunning));

    // QString statusText = qvariant_cast<QString>(index.data(FolderStatus));
    bool syncEnabled = index.data(FolderAccountConnected).toBool();
    // QString syncStatus = syncEnabled? tr( "Enabled" ) : tr( "Disabled" );

    QRect iconRect = option.rect;
    QRect aliasRect = option.rect;

    iconRect.setLeft( option.rect.left() + aliasMargin );
    iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2);

    // alias box
    aliasRect.setTop(aliasRect.top() + aliasMargin );
    aliasRect.setBottom(aliasRect.top() + aliasFm.height());
    aliasRect.setRight(aliasRect.right() - aliasMargin );

    // remote directory box
    QRect remotePathRect = aliasRect;
    remotePathRect.setTop(aliasRect.bottom() + margin );
    remotePathRect.setBottom(remotePathRect.top() + subFm.height());

    // local directory box
    QRect localPathRect = remotePathRect;
    localPathRect.setTop( remotePathRect.bottom() + margin );
    localPathRect.setBottom( localPathRect.top() + subFm.height());

    iconRect.setBottom(localPathRect.bottom());
    iconRect.setWidth(iconRect.height());

    int nextToIcon = iconRect.right()+aliasMargin;
    aliasRect.setLeft(nextToIcon);
    localPathRect.setLeft(nextToIcon);
    remotePathRect.setLeft(nextToIcon);

    int iconSize = iconRect.width();

    QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled );
    painter->drawPixmap(QPoint(iconRect.left(), iconRect.top()), pm);

    // only show the warning icon if the sync is running. Otherwise its
    // encoded in the status icon.
    if( warningCount > 0 && syncOngoing) {
        QRect warnRect;
        warnRect.setLeft(iconRect.left());
        warnRect.setTop(iconRect.bottom()-17);
        warnRect.setWidth(16);
        warnRect.setHeight(16);

        QIcon warnIcon(":/client/resources/warning");
        QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
        painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
    }

    auto palette = option.palette;

    if (qApp->style()->inherits("QWindowsVistaStyle")) {
        // Hack: Windows Vista's light blue is not contrasting enough for white

        // (code from QWindowsVistaStyle::drawControl for CE_ItemViewItem)
        palette.setColor(QPalette::All, QPalette::HighlightedText, palette.color(QPalette::Active, QPalette::Text));
        palette.setColor(QPalette::All, QPalette::Highlight, palette.base().color().darker(108));
    }


    QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
                            ? QPalette::Normal : QPalette::Disabled;
    if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
        cg = QPalette::Inactive;

    if (option.state & QStyle::State_Selected) {
        painter->setPen(palette.color(cg, QPalette::HighlightedText));
    } else {
        painter->setPen(palette.color(cg, QPalette::Text));
    }
    QString elidedAlias = aliasFm.elidedText(aliasText, Qt::ElideRight, aliasRect.width());
    painter->setFont(aliasFont);
    painter->drawText(aliasRect, elidedAlias);

    const bool showProgess = !overallString.isEmpty() || !itemString.isEmpty();
    if(!showProgess) {
        painter->setFont(subFont);
        QString elidedRemotePathText;

        if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
            elidedRemotePathText = subFm.elidedText(tr("Syncing selected files in your account with"),
                                                    Qt::ElideRight, remotePathRect.width());
        } else {
            elidedRemotePathText = subFm.elidedText(tr("Remote path: %1").arg(remotePath),
                                                    Qt::ElideMiddle, remotePathRect.width());
        }
        painter->drawText(remotePathRect, elidedRemotePathText);

        QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
        painter->drawText(localPathRect, elidedPathText);
    }

    // paint an error overlay if there is an error string

    int h = iconRect.bottom();
    if( !errorTexts.isEmpty() ) {
        h += aliasMargin;
        QRect errorRect = localPathRect;
        errorRect.setLeft( iconRect.left());
        errorRect.setTop( h );
        errorRect.setHeight(errorTexts.count() * subFm.height()+aliasMargin);
        errorRect.setRight( option.rect.right()-aliasMargin );

        painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
        painter->setPen( QColor(0xaa, 0xaa, 0xaa));
        painter->drawRoundedRect( errorRect, 4, 4 );

        painter->setPen( Qt::white );
        painter->setFont(errorFont);
        QRect errorTextRect = errorRect;
        errorTextRect.setLeft( errorTextRect.left()+aliasMargin );
        errorTextRect.setTop( errorTextRect.top()+aliasMargin/2 );

        int x = errorTextRect.left();
        int y = errorTextRect.top()+aliasMargin/2 + subFm.height()/2;

        foreach( QString eText, errorTexts ) {
            painter->drawText(x, y, subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()-2*aliasMargin));
            y += subFm.height();
        }
void ExtensionListDelegate::updateEditorGeometry(QWidget* pEditor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
   QRect editRect = option.rect;
   editRect.setHeight(editRect.height() - 1.0); //leave space for border
   pEditor->setGeometry(editRect);
}
Example #16
0
/// Writes all the relevant data into the tdf file.
void ExportEPS::doExport()
{
  using namespace std;

  // code adapted from Umbrello
  bool exportSuccessful;
  QRect textrect;

  //out->close();

    // print the image to a normal postscript file,
    // do not clip so that everything ends up in the file
    // regardless of "paper size"

    // because we want to work with postscript
    // user-coordinates, set to the resolution
    // of the printer (which should be 72dpi here)
    QPrinter *printer;

    printer = new QPrinter(QPrinter::ScreenResolution);

    printer->setOutputToFile(true);
    printer->setOutputFormat(QPrinter::PostScriptFormat);
    printer->setOutputFileName(fileName);
    printer->setColorMode(QPrinter::Color);
	printer->setFontEmbeddingEnabled(true);

    // do not call printer.setup(); because we want no user
    // interaction here
    QPainter *painter = new QPainter(printer);

    // make sure the widget sizes will be according to the
    // actually used printer font, important for getDiagramRect()
    // and the actual painting
    //view->forceUpdateWidgetFontMetrics(painter);

    if (!scrollview)
    {
      delete painter;
      delete printer;
      exportSuccessful = FALSE;
    }
    Draw* draw = new Draw(scrollview, options);
    QRect rect = draw->getBoundingBox(machine, painter);
	rect.setWidth(rect.width()+10);
	rect.setHeight(rect.height()+10);
    painter->translate(-rect.x(),-rect.y());
    //view->getDiagram(rect,*painter);

    int resolution = printer->resolution();


    if (scrollview)
      scrollview->getDrawArea()->getSelection()->deselectAll(machine);
    draw->drawStates(machine, painter, 0, 0, 1.0);
    draw->drawTransitions(machine, painter, 0, 0, 1.0);
    if (machine->getDrawITrans())
      draw->drawInitialTransition(machine, machine->getInitialTransition(), painter, 0, 0, 1.0, textrect, FALSE);

    // delete painter and printer before we try to open and fix the file
    delete painter;
    delete printer;
    delete draw;
    
    // modify bounding box from screen to eps resolution.
    rect.setWidth( int(ceil(rect.width() * 72.0/resolution)) );
    rect.setHeight( int(ceil(rect.height() * 72.0/resolution)) );
    exportSuccessful = fixEPS(fileName,rect);
	
    // next painting will most probably be to a different device (i.e. the screen)
    //view->forceUpdateWidgetFontMetrics(0);

    if (scrollview)
      scrollview->getDrawArea()->reset();
    //return exportSuccessful;
}
Example #17
0
QRect ctkDicomHostInterfaceImpl::getAvailableScreen(const QRect& preferredScreen)
{
  http.setAction("GetAvailableScreen");

  QtSoapMessage request;
  request.setMethod("GetAvailableScreen");

  QtSoapStruct* preferredScreenType = new QtSoapStruct(QtSoapQName("preferredScreen"));
  preferredScreenType->insert(new QtSoapSimpleType(QtSoapQName("Height"), preferredScreen.height()));
  preferredScreenType->insert(new QtSoapSimpleType(QtSoapQName("Width"), preferredScreen.width()));
  preferredScreenType->insert(new QtSoapSimpleType(QtSoapQName("RefPointX"), preferredScreen.x()));
  preferredScreenType->insert(new QtSoapSimpleType(QtSoapQName("RefPointY"), preferredScreen.y()));

  request.addMethodArgument(preferredScreenType);

  http.submitRequest(request, "/IHostService");

  qDebug() << "Submitted request GetAvailableScreen";

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  blockingLoop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);

  QApplication::restoreOverrideCursor();

  //qDebug() << "Reply error: " << reply->errorString();
  //qDebug() << reply->readAll();
  const QtSoapMessage& response = http.getResponse();

  if (response.isFault())
  {
    throw std::runtime_error("server error");
  }

  qDebug() << "Response: " << response.toXmlString();

  const QtSoapType &meth = response.method();

  if (!meth.isValid() || meth.type() != QtSoapType::Struct)
    qDebug() << "SOAP returning NIL: invalid or type != Struct";

  const QtSoapStruct &m = dynamic_cast<const QtSoapStruct &>(meth);
  if (m.count() == 0)
    qDebug() << "SOAP returning NIL: count == 0";


  const QtSoapType& screenResult = response.returnValue();
  if (!screenResult.isValid())
  {
    //throw std::runtime_error("invalid return value");
    qDebug() << response.errorString() << response.faultString().toString();
    qDebug() << response.toXmlString();
    return QRect();
  }

  qDebug() << screenResult.count() << screenResult["Height"].typeName();
  QRect resultRect;
  resultRect.setHeight(screenResult["Height"].toInt());
  resultRect.setWidth(screenResult["Width"].toInt());
  resultRect.setX(screenResult["RefPointX"].toInt());
  resultRect.setY(screenResult["RefPointY"].toInt());

  qDebug() << "x:" << resultRect.x() << " y:" << resultRect.y();

  return resultRect;
}
/** Overloads default QWidget::paintEvent. Draws the actual 
 * bandwidth graph. */
void RSPermissionMatrixWidget::paintEvent(QPaintEvent *)
{
    //std::cerr << "In paint event!" << std::endl;

  /* Set current graph dimensions */
  _rec = this->frameRect();
  
  /* Start the painter */
  _painter->begin(this);
  
  /* We want antialiased lines and text */
  _painter->setRenderHint(QPainter::Antialiasing);
  _painter->setRenderHint(QPainter::TextAntialiasing);
  
  /* Fill in the background */
  _painter->fillRect(_rec, QBrush(BACK_COLOR));
  _painter->drawRect(_rec);

  // draw one line per friend.
  std::list<RsPeerId> ssllist ;
  rsPeers->getFriendList(ssllist) ;

  // sort list
  {
      // RSPermissionMatrixWidgets parent is ServicePermissionsPage which holds the checkbox
      ServicePermissionsPage *spp = dynamic_cast<ServicePermissionsPage*>(parentWidget());
      if(spp != NULL) {
          // sort out offline peers
          if(spp->isHideOfflineChecked()) {
              RsPeerDetails peerDetails;
              for(std::list<RsPeerId>::iterator it = ssllist.begin(); it != ssllist.end();) {
                  rsPeers->getPeerDetails(*it, peerDetails);

                  switch (peerDetails.connectState) {
                  case RS_PEER_CONNECTSTATE_OFFLINE:
                  case RS_PEER_CONNECTSTATE_TRYING_TCP:
                  case RS_PEER_CONNECTSTATE_TRYING_UDP:
                      it = ssllist.erase(it);
                      break;
                  default:
                      it++;
                      break;
                  }
              }
          }
      }

      // sort by name
      ssllist.sort(sortRsPeerIdByNameLocation);
  }

  RsPeerServiceInfo ownServices;
  rsServiceControl->getOwnServices(ownServices);

  // Display friend names at the beginning of each column

  const QFont& font(_painter->font()) ;
  QFontMetrics fm(font);
  int peer_name_size = 0 ;
  float line_height = 2 + fm.height() ;

  std::vector<QString> names ;

  for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it)
  {
      RsPeerDetails details ;
      rsPeers->getPeerDetails(*it,details) ;

      QString name = QString::fromUtf8(details.name.c_str()) + " (" + QString::fromUtf8(details.location.c_str()) + ")";
      if(name.length() > 20)
          name = name.left(20)+"..." ;

      peer_name_size = std::max(peer_name_size, fm.width(name)) ;
      names.push_back(name) ;
  }

  QPen pen ;
  pen.setWidth(2) ;
  pen.setBrush(Qt::black) ;

  _painter->setPen(pen) ;
  int i=0;
  int x=5 ;
  int y=MATRIX_START_Y ;

  for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it,++i)
  {
      float X = MATRIX_START_X + peer_name_size - fm.width(names[i]) ;
      float Y = MATRIX_START_Y + (i+0.5)*ROW_SIZE + line_height/2.0f-2 ;

      _painter->drawText(QPointF(X,Y),names[i]) ;

      if(*it == _current_peer_id)
          _painter->drawLine(QPointF(X,Y+3),QPointF(X+fm.width(names[i]),Y+3)) ;

      y += line_height ;
  }

  matrix_start_x = 5 + MATRIX_START_X + peer_name_size ;

  // now draw the service names

  i=0 ;
  std::vector<int> last_width(10,0) ;

  for(std::map<uint32_t, RsServiceInfo>::const_iterator it(ownServices.mServiceList.begin());it!=ownServices.mServiceList.end();++it,++i)
  {
      QString name = QString::fromUtf8(it->second.mServiceName.c_str()) ;
      int text_width = fm.width(name) ;

      int X = matrix_start_x + COL_SIZE/2 - 2 + i*COL_SIZE - text_width/2;

      int height_index = 0 ;
      while(last_width[height_index] > X-5 && height_index < last_width.size()-1)
          ++height_index ;

      int Y = MATRIX_START_Y - ICON_SIZE_Y - 2 - line_height * height_index;

      last_width[height_index] = X + text_width ;
       // draw a half-transparent rectangle

      QBrush brush ;
      brush.setColor(QColor::fromHsvF(0.0f,0.0f,1.0f,0.8f));
      brush.setStyle(Qt::SolidPattern) ;

      QPen pen ;
      pen.setWidth(2) ;

      if(_current_service_id == it->second.mServiceType)
          pen.setBrush(Qt::black) ;
      else
          pen.setBrush(Qt::gray) ;

      _painter->setPen(pen) ;

      QRect info_pos( X-5,Y-line_height-2, text_width + 10, line_height + 5) ;

      //_painter->fillRect(info_pos,brush) ;
      //_painter->drawRect(info_pos) ;

      _painter->drawLine(QPointF(X,Y+3),QPointF(X+text_width,Y+3)) ;
      _painter->drawLine(QPointF(X+text_width/2, Y+3), QPointF(X+text_width/2,MATRIX_START_Y+peer_ids.size()*ROW_SIZE - ROW_SIZE+5)) ;

      pen.setBrush(Qt::black) ;
      _painter->setPen(pen) ;

      _painter->drawText(QPointF(X,Y),name);
  }

  // Now draw the global switches.

  peer_ids.clear() ;
  for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it)
      peer_ids.push_back(*it) ;
  service_ids.clear() ;
  for(std::map<uint32_t, RsServiceInfo>::const_iterator sit(ownServices.mServiceList.begin());sit!=ownServices.mServiceList.end();++sit)
      service_ids.push_back(sit->first) ;

  static const std::string global_switch[2] = { ":/images/global_switch_off.png",
                                                ":/images/global_switch_on.png" } ;

  for(int i=0;i<service_ids.size();++i)
  {
      RsServicePermissions serv_perm ;
      rsServiceControl->getServicePermissions(service_ids[i],serv_perm) ;

      QPixmap pix(global_switch[serv_perm.mDefaultAllowed].c_str()) ;
      QRect position = computeNodePosition(0,i,false) ;

      position.setY(position.y() - ICON_SIZE_Y + 8) ;
      position.setX(position.x() + 3) ;
      position.setHeight(30) ;
      position.setWidth(30) ;

      _painter->drawPixmap(position,pix,QRect(0,0,30,30)) ;
  }

  // We draw for each service.

  static const std::string pixmap_names[4] = { ":/images/switch00.png",
                                               ":/images/switch01.png",
                                               ":/images/switch10.png",
                                               ":/images/switch11.png" } ;

  int n_col = 0 ;
  int n_col_selected = -1 ;
  int n_row_selected = -1 ;

  for(std::map<uint32_t, RsServiceInfo>::const_iterator sit(ownServices.mServiceList.begin());sit!=ownServices.mServiceList.end();++sit,++n_col)
  {
      RsServicePermissions service_perms ;

      rsServiceControl->getServicePermissions(sit->first,service_perms) ;

      // draw the default switch.


      // draw one switch per friend.

      int n_row = 0 ;

      for(std::list<RsPeerId>::const_iterator it(ssllist.begin());it!=ssllist.end();++it,++n_row)
      {
          RsPeerServiceInfo local_service_perms ;
          RsPeerServiceInfo remote_service_perms ;

          rsServiceControl->getServicesAllowed (*it, local_service_perms) ;
          rsServiceControl->getServicesProvided(*it,remote_service_perms) ;

          bool  local_allowed =  local_service_perms.mServiceList.find(sit->first) !=  local_service_perms.mServiceList.end() ;
          bool remote_allowed = remote_service_perms.mServiceList.find(sit->first) != remote_service_perms.mServiceList.end() ;

      QPixmap pix(pixmap_names[(local_allowed << 1) + remote_allowed].c_str()) ;

      bool selected = (sit->first == _current_service_id && *it == _current_peer_id) ;
      QRect position = computeNodePosition(n_row,n_col,selected) ;

      if(selected)
      {
          n_row_selected = n_row ;
          n_col_selected = n_col ;
      }
          _painter->drawPixmap(position,pix,QRect(0,0,ICON_SIZE_X,ICON_SIZE_Y)) ;
      }
  }

  // now display some info about current node.

  if(n_row_selected < peer_ids.size() && n_col_selected < service_ids.size())
  {
      QRect position = computeNodePosition(n_row_selected,n_col_selected,false) ;

      // draw text info

      RsServicePermissions service_perms ;

      rsServiceControl->getServicePermissions(service_ids[n_col_selected],service_perms) ;

      QString service_name    = tr("Service name:")+" "+QString::fromUtf8(service_perms.mServiceName.c_str()) ;
      QString service_default = service_perms.mDefaultAllowed?tr("Allowed by default"):tr("Denied by default");
      QString peer_name = tr("Peer name:")+" " + names[n_row_selected] ;
      QString peer_id = tr("Peer Id:")+" "+QString::fromStdString(_current_peer_id.toStdString()) ;

      RsPeerServiceInfo pserv_info ;
      rsServiceControl->getServicesAllowed(_current_peer_id,pserv_info) ;

      bool locally_allowed = pserv_info.mServiceList.find(_current_service_id) != pserv_info.mServiceList.end();
      bool remotely_allowed = false ; // default, if the peer is offline

      if(rsServiceControl->getServicesProvided(_current_peer_id,pserv_info))
          remotely_allowed = pserv_info.mServiceList.find(_current_service_id) != pserv_info.mServiceList.end();

      QString local_status  = locally_allowed ?tr("Enabled for this peer") :tr("Disabled for this peer") ;
      QString remote_status = remotely_allowed?tr("Enabled by remote peer"):tr("Disabled by remote peer") ;

      if(!service_perms.mDefaultAllowed)
          local_status = tr("Switched Off") ;

      const QFont& font(_painter->font()) ;
      QFontMetrics fm(font);

      int text_size_x = 0 ;
      text_size_x = std::max(text_size_x,fm.width(service_name));
      text_size_x = std::max(text_size_x,fm.width(peer_name));
      text_size_x = std::max(text_size_x,fm.width(peer_id));
      text_size_x = std::max(text_size_x,fm.width(local_status));
      text_size_x = std::max(text_size_x,fm.width(remote_status));

       // draw a half-transparent rectangle

      QBrush brush ;
      brush.setColor(QColor::fromHsvF(0.0f,0.0f,1.0f,0.8f));
      brush.setStyle(Qt::SolidPattern) ;

      QPen pen ;
      pen.setWidth(2) ;
      pen.setBrush(Qt::black) ;

      _painter->setPen(pen) ;

      QRect info_pos( position.x() + 50, position.y() - 10, text_size_x + 10, line_height * 5 + 5) ;

      _painter->fillRect(info_pos,brush) ;
      _painter->drawRect(info_pos) ;

      // draw the text

      float x = info_pos.x() + 5 ;
      float y = info_pos.y() + line_height + 1 ;

      _painter->drawText(QPointF(x,y), service_name)  ; y += line_height ;
      _painter->drawText(QPointF(x,y), peer_name)     ; y += line_height ;
      _painter->drawText(QPointF(x,y), peer_id)       ; y += line_height ;
      _painter->drawText(QPointF(x,y), remote_status) ; y += line_height ;
      _painter->drawText(QPointF(x,y), local_status)  ; y += line_height ;
  }

  _max_height = MATRIX_START_Y + (peer_ids.size()+3) * ROW_SIZE ;
  _max_width  = matrix_start_x + (service_ids.size()+3) * COL_SIZE ;

  /* Stop the painter */
  _painter->end();
}
Example #19
0
void
QueryLabel::mouseMoveEvent( QMouseEvent* event )
{
    QFrame::mouseMoveEvent( event );
    int x = event->x();

    if ( event->buttons() & Qt::LeftButton &&
       ( m_dragPos - event->pos() ).manhattanLength() >= QApplication::startDragDistance() )
    {
        startDrag();
        leaveEvent( 0 );
        return;
    }

    if ( m_query.isNull() && m_result.isNull() )
    {
        m_hoverArea = QRect();
        m_hoverType = None;
        return;
    }

    QFontMetrics fm = fontMetrics();
    if ( m_useCustomFont )
        fm = QFontMetrics( m_font );

    int dashX = fm.width( DASH );
    int artistX = m_type & Artist ? fm.width( artist() ) : 0;
    int albumX = m_type & Album ? fm.width( album() ) : 0;
    int trackX = m_type & Track ? fm.width( track() ) : 0;

    if ( m_type & Track )
    {
        trackX += contentsMargins().left();
    }
    if ( m_type & Album )
    {
        trackX += albumX + dashX;
        albumX += contentsMargins().left();
    }
    if ( m_type & Artist )
    {
        albumX += artistX + dashX;
        trackX += artistX + dashX;
        artistX += contentsMargins().left();
    }

    QRect hoverArea;
    m_hoverType = None;

    if ( m_align & Qt::AlignLeft )
    {
        if ( m_type & Artist && x < artistX )
        {
            m_hoverType = Artist;
            hoverArea.setLeft( 0 );
            hoverArea.setRight( artistX + contentsMargins().left() - 1 );
        }
        else if ( m_type & Album && x < albumX && x > artistX )
        {
            m_hoverType = Album;
            int spacing = ( m_type & Artist ) ? dashX : 0;
            hoverArea.setLeft( artistX + spacing );
            hoverArea.setRight( albumX + spacing + contentsMargins().left() - 1 );
        }
        else if ( m_type & Track && x < trackX && x > albumX )
        {
            m_hoverType = Track;
            int spacing = ( m_type & Album ) ? dashX : 0;
            hoverArea.setLeft( albumX + spacing );
            hoverArea.setRight( trackX + contentsMargins().left() - 1 );
        }
        else if ( m_jumpLinkVisible && x < trackX + 6 + m_jumpPixmap.width() && x > trackX + 6 )
        {
            m_hoverType = Complete;
        }
    }
    else
    {
        hoverArea.setLeft( 0 );
        hoverArea.setRight( width() - 1 );
        
        if ( m_type & Artist )
            m_hoverType = Artist;
        else if ( m_type & Album )
            m_hoverType = Album;
        else if ( m_type & Track )
            m_hoverType = Track;
    }

    if ( hoverArea.width() )
    {
        hoverArea.setY( 1 );
        hoverArea.setHeight( height() - 2 );
    }
    
    if ( m_hoverType != None )
        setCursor( Qt::PointingHandCursor );
    else
        setCursor( Qt::ArrowCursor );

    if ( hoverArea != m_hoverArea )
    {
        m_hoverArea = hoverArea;
        repaint();
    }
}
Example #20
0
QRect KToonStyle::subControlRect(ComplexControl control, const QStyleOptionComplex *option, SubControl subControl, const QWidget *widget) const
{
	QRect rect;

	switch (control)
	{
		default:
		{
			rect = QPlastiqueStyle::subControlRect(control, option, subControl, widget);
			break;
		}
#if QT_VERSION >= 0x040100
		case CC_GroupBox:
		{
			if (const QStyleOptionGroupBox *group = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) 
			{
				switch (subControl) 
				{
					default:
						rect = QPlastiqueStyle::subControlRect(control, option, subControl, widget);
						break;
#if QT_VERSION >= 0x040100
					case SC_GroupBoxContents:
						rect = QPlastiqueStyle::subControlRect(control, option, subControl, widget);
						if ( group->text.length() < 4)
						{
							rect.adjust(0, 4, 0, 0);
						}
						else
						{
							rect.adjust(0, -10, 0, 0);
						}
						break;
#endif
					case SC_GroupBoxFrame:
						rect = group->rect;
						break;
					case SC_GroupBoxLabel:
						QPixmap titleLeft = cached(":res/images/title_cap_left.png");
						QPixmap titleRight = cached(":res/images/title_cap_right.png");
						QPixmap titleStretch = cached(":res/images/title_stretch.png");
						int txt_width = group->fontMetrics.width(group->text) + 20;
						rect = QRect(group->rect.center().x() - txt_width/2 + titleLeft.width(), 0,
								txt_width - titleLeft.width() - titleRight.width(),
								titleStretch.height());
						break;
				}
			}
			break;
		}
#endif
	}

	if (control == CC_Slider && subControl == SC_SliderHandle) 
	{
		rect.setWidth(13);
		rect.setHeight(27);
	} 
	else if (control == CC_Slider && subControl == SC_SliderGroove) 
	{
		rect.setHeight(9);
		rect.moveTop(27/2 - 9/2);
	}
	return rect;
}
Example #21
0
void
QueryLabel::mouseMoveEvent( QMouseEvent* event )
{
    QFrame::mouseMoveEvent( event );
    int x = event->x();

    if ( event->buttons() & Qt::LeftButton &&
       ( m_dragPos - event->pos() ).manhattanLength() >= QApplication::startDragDistance() )
    {
        startDrag();
        leaveEvent( 0 );
        return;
    }

    if ( m_query.isNull() && m_result.isNull() )
    {
        m_hoverArea = QRect();
        m_hoverType = None;
        return;
    }

    const QFontMetrics& fm = fontMetrics();
    int dashX = fm.width( DASH );
    int artistX = m_type & Artist ? fm.width( artist() ) : 0;
    int albumX = m_type & Album ? fm.width( album() ) : 0;
    int trackX = m_type & Track ? fm.width( track() ) : 0;

    if ( m_type & Track )
    {
        trackX += contentsMargins().left();
    }
    if ( m_type & Album )
    {
        trackX += albumX + dashX;
        albumX += contentsMargins().left();
    }
    if ( m_type & Artist )
    {
        albumX += artistX + dashX;
        trackX += artistX + dashX;
        artistX += contentsMargins().left();
    }

    QRect hoverArea;
    m_hoverType = None;
    if ( m_type & Artist && x < artistX )
    {
        m_hoverType = Artist;
        hoverArea.setLeft( 0 );
        hoverArea.setRight( artistX + contentsMargins().left() - 1 );
    }
    else if ( m_type & Album && x < albumX && x > artistX )
    {
        m_hoverType = Album;
        int spacing = ( m_type & Artist ) ? dashX : 0;
        hoverArea.setLeft( artistX + spacing );
        hoverArea.setRight( albumX + spacing + contentsMargins().left() - 1 );
    }
    else if ( m_type & Track && x < trackX && x > albumX )
    {
        m_hoverType = Track;
        int spacing = ( m_type & Album ) ? dashX : 0;
        hoverArea.setLeft( albumX + spacing );
        hoverArea.setRight( trackX + contentsMargins().left() - 1 );
    }

    if ( hoverArea.width() )
    {
        hoverArea.setY( 1 );
        hoverArea.setHeight( height() - 2 );
    }
    if ( hoverArea != m_hoverArea )
    {
        m_hoverArea = hoverArea;
        repaint();
    }
}
Example #22
0
void KToonStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,QPainter *painter, const QWidget *widget) const
{
	Q_ASSERT(option);
	
	
	switch (element)
	{
		case PE_FrameFocusRect: break;
		case PE_IndicatorRadioButton:
		{
			if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option))
			{
				bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver);
				painter->save();
				QPixmap radio;
				if (hover)
					drawHoverRect(painter, widget->rect());

				if (button->state & State_Sunken)
					radio = cached(":res/images/radiobutton-on.png");
				else if (button->state & State_On)
					radio = cached(":res/images/radiobutton_on.png");
				else
					radio = cached(":res/images/radiobutton_off.png");
				painter->drawPixmap(button->rect.topLeft(), radio);

				painter->restore();
			}
			else
			{
				QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
			}
			break;
		}
		case PE_PanelButtonCommand:
		{
			const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(option);
			if (button)
			{
				bool hover = (button->state & State_Enabled) && (button->state & State_MouseOver);

				painter->save();
				const QPushButton *pushButton = qobject_cast<const QPushButton *>(widget);
				
				if ( ! pushButton  )
				{
					QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
					break;
				}
				
				QWidget *parent = pushButton->parentWidget();
				if (parent && qobject_cast<QGroupBox *>(parent))
				{
					QLinearGradient lg(0, 0, 0, parent->height());
					lg.setColorAt(0, QColor(224,224,224));
					lg.setColorAt(1, QColor(255,255,255));
					painter->setPen(Qt::NoPen);
					painter->setBrush(lg);
					painter->setBrushOrigin(-widget->mapToParent(QPoint(0,0)));
					painter->drawRect(button->rect);
					painter->setBrushOrigin(0,0);
				}
								
				bool down = pushButton && ((button->state & State_Sunken) || (button->state & State_On));
				
				bool goodSize = pushButton && pushButton->height() > 22;
				
				QPixmap left, right, mid;
				if (down && goodSize)
				{
					left = cached(":res/images/button_pressed_cap_left.png");
					
					right = cached(":res/images/button_pressed_cap_right.png");
					mid = cached(":res/images/button_pressed_stretch.png");
				} 
				else if (goodSize)
				{
					left = cached(":res/images/button_normal_cap_left.png");
					right = cached(":res/images/button_normal_cap_right.png");
					mid = cached(":res/images/button_normal_stretch.png");
				}
				
				if ( goodSize )
				{
					painter->drawPixmap(button->rect.topLeft(), left);
					painter->drawTiledPixmap(QRect(button->rect.x() + left.width(),button->rect.y(),button->rect.width() - left.width() - right.width(),
							left.height()),
					mid);
					painter->drawPixmap(button->rect.x() + button->rect.width() - right.width(),
							button->rect.y(),
							right);
				}
				
				if (hover)
				{
					painter->fillRect(widget->rect().adjusted(3,5,-3,-5), QColor(41,57,127,63));
				}
				painter->restore();
				
				if ( !goodSize )
				{
					QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
				}
			}
			else
			{
				QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
			}
			break;
		}
		case PE_FrameGroupBox:
		{
#if QT_VERSION >= 0x040100
			const QStyleOptionFrameV2 *group = qstyleoption_cast<const QStyleOptionFrameV2 *>(option);
			if (group)
			{
				const QRect &r = group->rect;
				if ( r.height() < 14 ) // FIXME FIXME FIXME
				{
					QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
					return;
				}
				
				painter->save();
				int radius = 14;
				int radius2 = radius*2;
				QPainterPath clipPath;
				clipPath.moveTo(radius, 0);
				clipPath.arcTo(r.right() - radius2, 0, radius2, radius2, 90, -90);
				clipPath.arcTo(r.right() - radius2, r.bottom() - radius2, radius2, radius2, 0, -90);
				clipPath.arcTo(r.left(), r.bottom() - radius2, radius2, radius2, 270, -90);
				clipPath.arcTo(r.left(), r.top(), radius2, radius2, 180, -90);
				painter->setClipPath(clipPath);
				QPixmap titleStretch = cached(":res/images/title_stretch.png");
				QPixmap topLeft = cached(":res/images/groupframe_topleft.png");
				QPixmap topRight = cached(":res/images/groupframe_topright.png");
				QPixmap bottomLeft = cached(":res/images/groupframe_bottom_left.png");
				QPixmap bottomRight = cached(":res/images/groupframe_bottom_right.png");
				QPixmap leftStretch = cached(":res/images/groupframe_left_stretch.png");
				QPixmap topStretch = cached(":res/images/groupframe_top_stretch.png");
				QPixmap rightStretch = cached(":res/images/groupframe_right_stretch.png");
				QPixmap bottomStretch = cached(":res/images/groupframe_bottom_stretch.png");
				QLinearGradient lg(0, 0, 0, r.height());
				
				lg.setColorAt(0, widget->palette().color(QPalette::Background));
				lg.setColorAt(1, widget->palette().color(QPalette::Light) );
				
				painter->setPen(Qt::NoPen);
				painter->setBrush(lg);
				painter->drawRect(r.adjusted(0, titleStretch.height()/2, 0, 0));
				painter->setClipping(false);

				int topFrameOffset = titleStretch.height()/2 - 2;
				painter->drawPixmap(r.topLeft() + QPoint(0, topFrameOffset), topLeft);
				painter->drawPixmap(r.topRight() - QPoint(topRight.width()-1, 0)
						+ QPoint(0, topFrameOffset), topRight);
				painter->drawPixmap(r.bottomLeft() - QPoint(0, bottomLeft.height()-1), bottomLeft);
				painter->drawPixmap(r.bottomRight() - QPoint(bottomRight.width()-1,
						bottomRight.height()-1), bottomRight);

				QRect left = r;
				left.setY(r.y() + topLeft.height() + topFrameOffset);
				left.setWidth(leftStretch.width());
				left.setHeight(r.height() - topLeft.height() - bottomLeft.height() - topFrameOffset);
				painter->drawTiledPixmap(left, leftStretch);

				QRect top = r;
				top.setX(r.x() + topLeft.width());
				top.setY(r.y() + topFrameOffset);
				top.setWidth(r.width() - topLeft.width() - topRight.width());
				top.setHeight(topLeft.height());
				painter->drawTiledPixmap(top, topStretch);

				QRect right = r;
				right.setX(r.right() - rightStretch.width()+1);
				right.setY(r.y() + topRight.height() + topFrameOffset);
				right.setWidth(rightStretch.width());
				right.setHeight(r.height() - topRight.height()
						- bottomRight.height() - topFrameOffset);
				painter->drawTiledPixmap(right, rightStretch);

				QRect bottom = r;
				bottom.setX(r.x() + bottomLeft.width());
				bottom.setY(r.bottom() - bottomStretch.height()+1);
				bottom.setWidth(r.width() - bottomLeft.width() - bottomRight.width());
				bottom.setHeight(bottomLeft.height());
				painter->drawTiledPixmap(bottom, bottomStretch);
				painter->restore();
			}
			else
			{
				QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
			}
#else
			QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
#endif
			break;
		}
		default:
			QPlastiqueStyle::drawPrimitive(element, option, painter, widget);
			break;
	}
	
	
	return;
}
Example #23
0
//
//  REDRAW CONTENTS
//
void MainWin::drawContents(QPainter *painter)
{
    int deltay,i;

    QRect r = contentsRect();

    deltay = r.height() / CurvCnt - 1;

    r.setHeight(deltay);

    //
    //  draw curves
    //
    for (i=0;i<CurvCnt;i++)
    {
        xMap.setPaintInterval(r.left(), r.right());
        yMap.setPaintInterval(r.top(), r.bottom());

#if QT_VERSION >= 0x040000
        painter->setRenderHint(QPainter::Antialiasing,
            crv[i].testRenderHint(QwtPlotItem::RenderAntialiased) );
#endif
        crv[i].draw(painter, xMap, yMap, r);

        shiftDown(r, deltay);
    }

    //
    // draw titles
    //
    r = contentsRect();     // reset r
    painter->setFont(QFont("Helvetica", 8));
    
    const int alignment = Qt::AlignTop|Qt::AlignHCenter;

    painter->setPen(Qt::black);

    painter->drawText(0,r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: Line/Fitted, Symbol: Cross");
    shiftDown(r, deltay);

    painter->drawText(0,r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: Sticks, Symbol: Ellipse");
    shiftDown(r, deltay);
    
    painter->drawText(0 ,r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: Lines, Symbol: None");
    shiftDown(r, deltay);

#if QT_VERSION >= 0x040000
    painter->drawText(0 ,r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: Lines, Symbol: None, Antialiased");
    shiftDown(r, deltay);
#endif
    
    
    painter->drawText(0, r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: Steps, Symbol: None");
    shiftDown(r, deltay);
    
    painter->drawText(0,r.top(),r.width(), painter->fontMetrics().height(),
        alignment, "Style: NoCurve, Symbol: XCross");
}
Example #24
0
void nxtCanvasWidget::action( action_event event ){
	static QPoint prev_last_mouse;
	
	if( active_tool == TOOL_NONE )
		return;
	
	//First handle the events that doesn't change the canvas
	if( active_tool == TOOL_SELECTION ){
		selection = get_qrect_from_points( mouse_start, mouse_current );
		if( selection.height() >= 0 )
			selection.setHeight( selection.height()+1 );
		if( selection.width() >= 0 )
			selection.setWidth( selection.width()+1 );
		update();
		//TODO: emit signal?
	}
	else if( active_tool == TOOL_MOVE ){
		if( is_moveable && event != EVENT_MOVE )	//Prevent infinitive loop
			change_pos( mouse_current.x() - mouse_last.x(), mouse_current.y() - mouse_last.y() );
	}
	else
		if( canvas ){
			//Create a fresh buffer, unless we are drawing in freehand
			if( active_tool != TOOL_PIXEL )
				new_buffer();
			
			//If this is the last action, enable auto-resize
			//if( event == EVENT_MOUSE_UP )
				canvas->set_auto_resize( true );
				//TODO: enable, then restore to previous state
			
			switch( active_tool ){
				case TOOL_PIXEL:
						//Draw a dot first time, then follow with lines
						if( event == EVENT_MOUSE_DOWN )
							canvas->PointOut( mouse_current.x(), mouse_current.y(), options );
						else
							canvas->connected_line_out( prev_last_mouse.x(), prev_last_mouse.y(), mouse_last.x(), mouse_last.y(), mouse_current.x(), mouse_current.y(), options );
						
						prev_last_mouse = mouse_last;
					break;
					
				case TOOL_LINE:
						if( key_control ){	//Limit to angles in steps of 15 degrees
							int dx = mouse_current.x() - mouse_start.x();
							int dy = mouse_current.y() - mouse_start.y();
							
							double angle = atan2( (double)( dy ), (double)( dx ) );
							double lenght = sqrt( (double)( dx*dx + dy*dy ) );
							double limiter = PI * 15 / 180;
							double new_angle = round_sym( angle / limiter ) * limiter;
							dy = round_sym( sin( new_angle ) * lenght );
							dx = round_sym( cos( new_angle ) * lenght );
							
							canvas->LineOut( mouse_start.x(), mouse_start.y(), mouse_start.x() + dx, mouse_start.y() + dy, options );
						}
						else
							canvas->LineOut( mouse_start.x(), mouse_start.y(), mouse_current.x(), mouse_current.y(), options );
					break;
				
				case TOOL_RECT:{
						QRect rect = get_qrect_from_points( mouse_start, mouse_current );
						
						//Make it a square if control is pressed
						if( key_control ){
							if( rect.width() > rect.height() ){
								if( mouse_current.y() < mouse_start.y() )
									rect.translate( 0, rect.height() - rect.width() );
								rect.setHeight( rect.width() );
							}
							else{
								if( mouse_current.x() < mouse_start.x() )
									rect.translate( rect.width() - rect.height(), 0 );
								rect.setWidth( rect.height() );
							}
						}
						
						canvas->RectOut( rect.x(), rect.y(), rect.width(), rect.height(), options );
					} break;
					
				case TOOL_ELLIPSE:
						if( key_control ){
							QPoint lenght = mouse_current - mouse_start;
							int radius = sqrt( (double)( lenght.x()*lenght.x() + lenght.y()*lenght.y() ) );
							canvas->CircleOut( mouse_start.x(), mouse_start.y(), radius, options );
						}
						else
							canvas->EllipseOut( mouse_start.x(), mouse_start.y(), abs( mouse_current.x() - mouse_start.x() ), abs( mouse_current.y() - mouse_start.y() ), options );
						break;
				
				case TOOL_BITMAP:{
						if( clipboard ){
							if( event == EVENT_MOUSE_DOWN ){
								selection.setWidth( clipboard->get_width() );
								selection.setHeight( clipboard->get_height() );
							}
							selection.moveTo( selection.topLeft() + mouse_current - mouse_last );
							canvas->copy_canvas( clipboard, 0, 0, selection.width(), selection.height(), selection.x(), selection.y(), options );
						}
					} break;
				
				case TOOL_FILL:	canvas->bucket_fill( mouse_current.x(), mouse_current.y(), options ); break;
				
				default: qDebug( "nxtCanvasWidget::action() unhandled tool: %d", active_tool );
			}
			
			//If this is the last action, make the buffer permanent
			if( event == EVENT_MOUSE_UP && active_tool != TOOL_BITMAP ){
			//	canvas->set_auto_resize( false );
				write_buffer();
			}
			
			update();
			emit value_changed();
		}
	
	
}
Example #25
0
void Image3DOverlay::render(RenderArgs* args) {
    if (!_renderVisible || !getParentVisible() || !_texture || !_texture->isLoaded()) {
        return;
    }

    // Once the texture has loaded, check if we need to update the render item because of transparency
    if (!_textureIsLoaded && _texture && _texture->getGPUTexture()) {
        _textureIsLoaded = true;
        bool prevAlphaTexture = _alphaTexture;
        _alphaTexture = _texture->getGPUTexture()->getUsage().isAlpha();
        if (_alphaTexture != prevAlphaTexture) {
            auto itemID = getRenderItemID();
            if (render::Item::isValidID(itemID)) {
                render::ScenePointer scene = AbstractViewStateInterface::instance()->getMain3DScene();
                render::Transaction transaction;
                transaction.updateItem(itemID);
                scene->enqueueTransaction(transaction);
            }
        }
    }

    Q_ASSERT(args->_batch);
    gpu::Batch* batch = args->_batch;

    float imageWidth = _texture->getWidth();
    float imageHeight = _texture->getHeight();

    QRect fromImage;
    if (_fromImage.isNull()) {
        fromImage.setX(0);
        fromImage.setY(0);
        fromImage.setWidth(imageWidth);
        fromImage.setHeight(imageHeight);
    } else {
        float scaleX = imageWidth / _texture->getOriginalWidth();
        float scaleY = imageHeight / _texture->getOriginalHeight();

        fromImage.setX(scaleX * _fromImage.x());
        fromImage.setY(scaleY * _fromImage.y());
        fromImage.setWidth(scaleX * _fromImage.width());
        fromImage.setHeight(scaleY * _fromImage.height());
    }

    float maxSize = glm::max(fromImage.width(), fromImage.height());
    float x = _keepAspectRatio ? fromImage.width() / (2.0f * maxSize) : 0.5f;
    float y = _keepAspectRatio ? -fromImage.height() / (2.0f * maxSize) : -0.5f;

    glm::vec2 topLeft(-x, -y);
    glm::vec2 bottomRight(x, y);
    glm::vec2 texCoordTopLeft((fromImage.x() + 0.5f) / imageWidth, (fromImage.y() + 0.5f) / imageHeight);
    glm::vec2 texCoordBottomRight((fromImage.x() + fromImage.width() - 0.5f) / imageWidth,
                                  (fromImage.y() + fromImage.height() - 0.5f) / imageHeight);

    float alpha = getAlpha();
    glm::u8vec3 color = getColor();
    glm::vec4 imageColor(toGlm(color), alpha);

    batch->setModelTransform(getRenderTransform());
    batch->setResourceTexture(0, _texture->getGPUTexture());

    DependencyManager::get<GeometryCache>()->renderQuad(
        *batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight,
        imageColor, _geometryId
    );

    batch->setResourceTexture(0, nullptr); // restore default white color after me
}
Example #26
0
void BillboardOverlay::render(RenderArgs* args) {
    if (!_isLoaded) {
        _isLoaded = true;
        _texture = DependencyManager::get<TextureCache>()->getTexture(_url);
    }

    if (!_visible || !_texture->isLoaded()) {
        return;
    }

    glm::quat rotation;
    if (_isFacingAvatar) {
        // rotate about vertical to face the camera
        rotation = args->_viewFrustum->getOrientation();
        rotation *= glm::angleAxis(glm::pi<float>(), IDENTITY_UP);
        rotation *= getRotation();
    } else {
        rotation = getRotation();
    }

    float imageWidth = _texture->getWidth();
    float imageHeight = _texture->getHeight();

    QRect fromImage;
    if (_fromImage.isNull()) {
        fromImage.setX(0);
        fromImage.setY(0);
        fromImage.setWidth(imageWidth);
        fromImage.setHeight(imageHeight);
    } else {
        float scaleX = imageWidth / _texture->getOriginalWidth();
        float scaleY = imageHeight / _texture->getOriginalHeight();

        fromImage.setX(scaleX * _fromImage.x());
        fromImage.setY(scaleY * _fromImage.y());
        fromImage.setWidth(scaleX * _fromImage.width());
        fromImage.setHeight(scaleY * _fromImage.height());
    }

    float maxSize = glm::max(fromImage.width(), fromImage.height());
    float x = fromImage.width() / (2.0f * maxSize);
    float y = -fromImage.height() / (2.0f * maxSize);

    glm::vec2 topLeft(-x, -y);
    glm::vec2 bottomRight(x, y);
    glm::vec2 texCoordTopLeft(fromImage.x() / imageWidth, fromImage.y() / imageHeight);
    glm::vec2 texCoordBottomRight((fromImage.x() + fromImage.width()) / imageWidth,
                                  (fromImage.y() + fromImage.height()) / imageHeight);

    const float MAX_COLOR = 255.0f;
    xColor color = getColor();
    float alpha = getAlpha();

    auto batch = args->_batch;

    if (batch) {
        Transform transform = _transform;
        transform.postScale(glm::vec3(getDimensions(), 1.0f));
        
        batch->setModelTransform(transform);
        batch->setUniformTexture(0, _texture->getGPUTexture());
        
        DependencyManager::get<GeometryCache>()->renderQuad(*batch, topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight,
                                                            glm::vec4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha));
    
        batch->setUniformTexture(0, args->_whiteTexture); // restore default white color after me
    } else {
        glEnable(GL_ALPHA_TEST);
        glAlphaFunc(GL_GREATER, 0.5f);

        glEnable(GL_TEXTURE_2D);
        glDisable(GL_LIGHTING);

        glBindTexture(GL_TEXTURE_2D, _texture->getID());

        glPushMatrix(); {
            glTranslatef(getPosition().x, getPosition().y, getPosition().z);
            glm::vec3 axis = glm::axis(rotation);
            glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z);
            glScalef(_dimensions.x, _dimensions.y, 1.0f);

            DependencyManager::get<GeometryCache>()->renderQuad(topLeft, bottomRight, texCoordTopLeft, texCoordBottomRight,
                                                                glm::vec4(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha));

        } glPopMatrix();

        glDisable(GL_TEXTURE_2D);
        glEnable(GL_LIGHTING);
        glDisable(GL_ALPHA_TEST);

        glBindTexture(GL_TEXTURE_2D, 0);
    }
}
Example #27
0
void Matrix::print(const QString& fileName)
{
	QPrinter printer;
	printer.setColorMode (QPrinter::GrayScale);

	if (!fileName.isEmpty()){
	    printer.setCreator("QtiPlot");
	    printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
	} else {
        QPrintDialog printDialog(&printer, applicationWindow());
        if (printDialog.exec() != QDialog::Accepted)
            return;
    }
		printer.setFullPage( true );
		QPainter p;
		if ( !p.begin(&printer ) )
			return; // paint on printer
		int dpiy = printer.logicalDpiY();
		const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins

        if (d_view_type == ImageView){
            p.drawImage (printer.pageRect(), d_matrix_model->renderImage());
            return;
        }

		QHeaderView *vHeader = d_table_view->verticalHeader();

		int rows = numRows();
		int cols = numCols();
		int height = margin;
		int i, vertHeaderWidth = vHeader->width();
		int right = margin + vertHeaderWidth;

		// print header
		p.setFont(QFont());
		QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString();
		QRect br = p.boundingRect(br, Qt::AlignCenter, header_label);
		p.drawLine(right, height, right, height+br.height());
		QRect tr(br);

		for(i=0; i<cols; i++){
			int w = d_table_view->columnWidth(i);
			tr.setTopLeft(QPoint(right,height));
			tr.setWidth(w);
			tr.setHeight(br.height());
			header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString();
			p.drawText(tr, Qt::AlignCenter, header_label,-1);
			right += w;
			p.drawLine(right, height, right, height+tr.height());

			if (right >= printer.width()-2*margin )
				break;
		}

		p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line
		height += tr.height();
		p.drawLine(margin, height, right-1, height);

		// print table values
		for(i=0;i<rows;i++){
			right = margin;
			QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t";
			tr = p.boundingRect(tr, Qt::AlignCenter, cell_text);
			p.drawLine(right, height, right, height+tr.height());

			br.setTopLeft(QPoint(right,height));
			br.setWidth(vertHeaderWidth);
			br.setHeight(tr.height());
			p.drawText(br,Qt::AlignCenter,cell_text,-1);
			right += vertHeaderWidth;
			p.drawLine(right, height, right, height+tr.height());

			for(int j=0; j<cols; j++){
				int w = d_table_view->columnWidth (j);
				cell_text = text(i,j)+"\t";
				tr = p.boundingRect(tr,Qt::AlignCenter,cell_text);
				br.setTopLeft(QPoint(right,height));
				br.setWidth(w);
				br.setHeight(tr.height());
				p.drawText(br, Qt::AlignCenter, cell_text, -1);
				right += w;
				p.drawLine(right, height, right, height+tr.height());

				if (right >= printer.width()-2*margin )
					break;
			}
			height += br.height();
			p.drawLine(margin, height, right-1, height);

			if (height >= printer.height()-margin ){
				printer.newPage();
				height = margin;
				p.drawLine(margin, height, right, height);
			}
		}
}
Example #28
0
void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
    QString title = VLCModel::getMeta( index, COLUMN_TITLE );
    QString duration = VLCModel::getMeta( index, COLUMN_DURATION );
    if( !duration.isEmpty() ) title += QString(" [%1]").arg( duration );

    QString artist = VLCModel::getMeta( index, COLUMN_ARTIST );
    QString album = VLCModel::getMeta( index, COLUMN_ALBUM );
    QString trackNum = VLCModel::getMeta( index, COLUMN_TRACK_NUMBER );
    QString artistAlbum = artist;
    if( !album.isEmpty() )
    {
        if( !artist.isEmpty() ) artistAlbum += ": ";
        artistAlbum += album;
        if( !trackNum.isEmpty() ) artistAlbum += QString( " [#%1]" ).arg( trackNum );
    }

    QPixmap artPix = VLCModel::getArtPixmap( index, QSize( LISTVIEW_ART_SIZE, LISTVIEW_ART_SIZE ) );

    //Draw selection rectangle and current playing item indication
    paintBackground( painter, option, index );

    QRect artRect( artPix.rect() );
    artRect.moveCenter( QPoint( artRect.center().x() + 3,
                                option.rect.center().y() ) );
    //Draw album art
    painter->drawPixmap( artRect, artPix );

    //Start drawing text
    painter->save();

    if( option.state & QStyle::State_Selected )
        painter->setPen( option.palette.color( QPalette::HighlightedText ) );

    QTextOption textOpt( Qt::AlignVCenter | Qt::AlignLeft );
    textOpt.setWrapMode( QTextOption::NoWrap );

    QFont f( index.data( Qt::FontRole ).value<QFont>() );

    //Draw title info
    f.setItalic( true );
    f.setBold( index.data( VLCModel::CURRENT_ITEM_ROLE ).toBool() );
    painter->setFont( f );
    QFontMetrics fm( painter->fontMetrics() );

    QRect textRect = option.rect.adjusted( LISTVIEW_ART_SIZE + 10, 0, -10, 0 );
    if( !artistAlbum.isEmpty() )
    {
        textRect.setHeight( fm.height() );
        textRect.moveBottom( option.rect.center().y() - 2 );
    }

    //Draw children indicator
    if( !index.data( VLCModel::LEAF_NODE_ROLE ).toBool() )
    {
        QPixmap dirPix = QPixmap( ":/type/node" );
        painter->drawPixmap( QPoint( textRect.x(), textRect.center().y() - dirPix.height() / 2 ),
                             dirPix );
        textRect.setLeft( textRect.x() + dirPix.width() + 5 );
    }

    painter->drawText( textRect,
                       fm.elidedText( title, Qt::ElideRight, textRect.width() ),
                       textOpt );

    // Draw artist and album info
    if( !artistAlbum.isEmpty() )
    {
        f.setItalic( false );
        painter->setFont( f );
        fm = painter->fontMetrics();

        textRect.moveTop( textRect.bottom() + 4 );
        textRect.setLeft( textRect.x() + 20 );

        painter->drawText( textRect,
                           fm.elidedText( artistAlbum, Qt::ElideRight, textRect.width() ),
                           textOpt );
    }

    painter->restore();
}
void QColorTabWidget::drawTabs( QPainter& p, QRect rc )
{
#define TAB_INTERVAL	(3)
#define TAB_MARGIN		(10)
    QRect rectTab;

    switch (m_eTabDirection)
    {
    case TabDirectionHorzLeftTop:
        rectTab.setY(rc.top());
        rectTab.setX(rc.left() + m_nBarOffset);
        break;
    case TabDirectionHorzRightTop:
        rectTab.setY(rc.top());
        rectTab.setX(rc.right() - m_nBarOffset + TAB_INTERVAL);
        break;
    case TabDirectionVertLeftTop:
        rectTab.setX(rc.left());
        rectTab.setY(rc.top() + m_nBarOffset);
        break;
    case TabDirectionVertLeftBottom:
        rectTab.setX(rc.left());
        rectTab.setY(rc.bottom() - m_nBarOffset + TAB_INTERVAL);
        break;
    }

    QSize szTab = calcTabSize( p, m_aryTabInfo.at(0) );
    if (isHorzTab())
    {
        m_sizeTabHeader.setWidth(szTab.width());
        rectTab.setHeight(m_sizeTabHeader.height());
    }
    else
    {
        m_sizeTabHeader.setHeight(szTab.height());
        rectTab.setWidth(m_sizeTabHeader.width());
    }

    int nMaxTabBarSize = rc.width() - m_nBarOffset * 2;
    nMaxTabBarSize -= m_pExtraWidget != NULL ? (isHorzTab() ? m_pExtraWidget->width() : m_pExtraWidget->height()) + TAB_MARGIN*2 : 0;
    int nTabBarSize = 0;

    m_nVisibleCount = 0;
    for (int nI = m_nMoveCount; nI < m_aryTabInfo.size() ; nI ++)
    {
        TabInfo& ti = m_aryTabInfo[nI];
        szTab = calcTabSize( p, ti );

        if (m_eTabDirection == TabDirectionHorzRightTop)
        {
            rectTab.setX( rectTab.x() - (szTab.width() + TAB_INTERVAL + TAB_MARGIN) );
        }
        else if (m_eTabDirection == TabDirectionVertLeftBottom)
        {
            rectTab.setY( rectTab.y() - (szTab.height() + TAB_INTERVAL + TAB_MARGIN) );
        }

        if (isHorzTab())
        {
            rectTab.setWidth(szTab.width() + TAB_MARGIN);   // margin x: 5px
            nTabBarSize += rectTab.width();
        }
        else
        {
            rectTab.setHeight(szTab.height() + TAB_MARGIN);
            nTabBarSize += rectTab.height();
        }

        if( nTabBarSize <= nMaxTabBarSize )
        {
            drawTab( p, rectTab, ti,
                m_nHoverTabIndex == nI ? true : false,
                m_nActiveTabIndex == nI ? true : false, isNotifyTab(nI) < 0 ? false : true );

            m_nVisibleCount++;
        }

        ti.rcArea = rectTab;

        if (m_eTabDirection == TabDirectionHorzLeftTop)
        {
            rectTab.setX( rectTab.x() + (rectTab.width() + TAB_INTERVAL) );
        }
        else if (m_eTabDirection == TabDirectionVertLeftTop)
        {
            rectTab.setY( rectTab.y() + (rectTab.height() + TAB_INTERVAL) );
        }
    }

    if( m_nVisibleCount < m_aryTabInfo.size() )
    {
        if( !m_btnLeftTab.isVisible() )
        {
            m_btnLeftTab.setVisible( true );
            m_btnRightTab.setVisible( true );
        }
    }
    else
    {
        if( m_btnLeftTab.isVisible() )
        {
            m_btnLeftTab.setVisible( false );
            m_btnRightTab.setVisible( false );
        }
    }

    QPen bodyPen( QColor(160, 160, 160), 1.f);
    QPen bodyShadowPen( QColor(160, 160, 160, 150), 2.f);

    p.setPen(bodyShadowPen);
    if (isHorzTab())
    {
        int nTop = rectTab.bottom();
        if (m_nActiveTabIndex >= 0 && (m_nActiveTabIndex >= m_nMoveCount && m_nActiveTabIndex < (m_nMoveCount+m_nVisibleCount)))
        {
            const TabInfo& ti = m_aryTabInfo.at(m_nActiveTabIndex);
            p.drawLine( rc.left(), nTop, ti.rcArea.left(), nTop );
            p.drawLine( ti.rcArea.right(), nTop, rc.right(), nTop );
        }
        else
        {
            p.drawLine( rc.left(), nTop, rc.right(), nTop );
        }

        if (m_nActiveTabIndex >= 0)
            p.fillRect( rc.left(), nTop, rc.width(), rc.bottom()-nTop, Qt::white );

        p.drawLine( rc.right(), nTop, rc.right(), rc.bottom() );
        p.drawLine( rc.right(), rc.bottom(), rc.left(), rc.bottom() );
        p.drawLine( rc.left(), rc.bottom(), rc.left(), nTop );
    }
    else
    {
        int nLeft = rectTab.right();
        if (m_nActiveTabIndex >= 0 && (m_nActiveTabIndex >= m_nMoveCount && m_nActiveTabIndex < (m_nMoveCount+m_nVisibleCount)))
        {
            const TabInfo& ti = m_aryTabInfo.at(m_nActiveTabIndex);
            p.drawLine( nLeft, rc.top(), nLeft, ti.rcArea.top() );
            p.drawLine( nLeft, ti.rcArea.bottom(), nLeft, rc.bottom() );
        }
        else
        {
            p.drawLine( nLeft, rc.top(), nLeft, rc.bottom() );
        }

        if (m_nActiveTabIndex >= 0)
            p.fillRect( nLeft, rc.top(), rc.right()-nLeft, rc.height(), Qt::white );

        p.drawLine( nLeft, rc.bottom(), rc.right(), rc.bottom() );
        p.drawLine( rc.right(), rc.bottom(), rc.right(), rc.top() );
        p.drawLine( rc.right(), rc.top(), nLeft, rc.top() );
    }

    p.setPen( bodyPen );

    if (isHorzTab())
    {
        int nTop = rectTab.bottom();
        if (m_nActiveTabIndex >= 0 && (m_nActiveTabIndex >= m_nMoveCount && m_nActiveTabIndex < (m_nMoveCount+m_nVisibleCount)))
        {
            const TabInfo& ti = m_aryTabInfo.at(m_nActiveTabIndex);
            p.drawLine( rc.left(), nTop, ti.rcArea.left(), nTop );
            p.drawLine( ti.rcArea.right(), nTop, rc.right(), nTop );
        }
        else
        {
            p.drawLine( rc.left(), nTop, rc.right(), nTop );
        }

        p.drawLine( rc.right(), nTop, rc.right(), rc.bottom() );
        p.drawLine( rc.right(), rc.bottom(), rc.left(), rc.bottom() );
        p.drawLine( rc.left(), rc.bottom(), rc.left(), nTop );
    }
    else
    {
        int nLeft = rectTab.right();
        if (m_nActiveTabIndex >= 0 && (m_nActiveTabIndex >= m_nMoveCount && m_nActiveTabIndex < (m_nMoveCount+m_nVisibleCount)))
        {
            const TabInfo& ti = m_aryTabInfo.at(m_nActiveTabIndex);
            p.drawLine( nLeft, rc.top(), nLeft, ti.rcArea.top() );
            p.drawLine( nLeft, ti.rcArea.bottom(), nLeft, rc.bottom() );
        }
        else
        {
            p.drawLine( nLeft, rc.top(), nLeft, rc.bottom() );
        }

        p.drawLine( nLeft, rc.bottom(), rc.right(), rc.bottom() );
        p.drawLine( rc.right(), rc.bottom(), rc.right(), rc.top() );
        p.drawLine( rc.right(), rc.top(), nLeft, rc.top() );
    }
}
void AppletDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option,
                           const QModelIndex& index) const
{
    QStyleOptionViewItemV4 opt(option);
    QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget);

    const int left = option.rect.left();
    const int top = option.rect.top();
    const int width = option.rect.width();
    const int height = calcItemHeight(option);

    bool leftToRight = (painter->layoutDirection() == Qt::LeftToRight);
    QIcon::Mode iconMode = QIcon::Normal;

    QColor foregroundColor = (option.state.testFlag(QStyle::State_Selected)) ?
        option.palette.color(QPalette::HighlightedText) : option.palette.color(QPalette::Text);

    // Painting main column
    QFont titleFont = option.font;
    titleFont.setBold(true);
    titleFont.setPointSize(titleFont.pointSize() + 2);

    QPixmap pixmap(width, height);
    pixmap.fill(Qt::transparent);
    QPainter p(&pixmap);
    p.translate(-option.rect.topLeft());

    QLinearGradient gradient;

    QString title = index.model()->data(index, Qt::DisplayRole).toString();
    QString description = index.model()->data(index, AppletDelegate::DescriptionRole).toString();

    // Painting

    // Text
    int textInner = 2 * UNIVERSAL_PADDING + MAIN_ICON_SIZE;

    p.setPen(foregroundColor);
    p.setFont(titleFont);
    p.drawText(left + (leftToRight ? textInner : 0),
               top, width - textInner, height / 2,
               Qt::AlignBottom | Qt::AlignLeft, title);
    p.setFont(option.font);
    p.drawText(left + (leftToRight ? textInner : 0),
               top + height / 2,
               width - textInner, height / 2,
               Qt::AlignTop | Qt::AlignLeft, description);

    // Main icon
    const QIcon& icon = qVariantValue<QIcon>(index.model()->data(index, Qt::DecorationRole));
    icon.paint(&p,
        leftToRight ? left + UNIVERSAL_PADDING : left + width - UNIVERSAL_PADDING - MAIN_ICON_SIZE,
        top + UNIVERSAL_PADDING, MAIN_ICON_SIZE, MAIN_ICON_SIZE, Qt::AlignCenter, iconMode);

    // Gradient part of the background - fading of the text at the end
    if (leftToRight) {
        gradient = QLinearGradient(left + width - UNIVERSAL_PADDING - FADE_LENGTH, 0,
                left + width - UNIVERSAL_PADDING, 0);
        gradient.setColorAt(0, Qt::white);
        gradient.setColorAt(1, Qt::transparent);
    } else {
        gradient = QLinearGradient(left + UNIVERSAL_PADDING, 0,
                left + UNIVERSAL_PADDING + FADE_LENGTH, 0);
        gradient.setColorAt(0, Qt::transparent);
        gradient.setColorAt(1, Qt::white);
    }

    QRect paintRect = option.rect;
    p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
    p.fillRect(paintRect, gradient);

    if (leftToRight) {
        gradient.setStart(left + width - FADE_LENGTH, 0);
        gradient.setFinalStop(left + width, 0);
    } else {
        gradient.setStart(left + UNIVERSAL_PADDING, 0);
        gradient.setFinalStop(left + UNIVERSAL_PADDING + FADE_LENGTH, 0);
    }
    paintRect.setHeight(UNIVERSAL_PADDING + MAIN_ICON_SIZE / 2);
    p.fillRect(paintRect, gradient);
    p.end();

    painter->drawPixmap(option.rect.topLeft(), pixmap);
}