Example #1
0
void statisticSource::drawStatisticsImage(QPixmap *img, StatisticsItemList statsList, StatisticsType statsType)
{
	QPainter painter(img);

	StatisticsItemList::iterator it;
	for (it = statsList.begin(); it != statsList.end(); ++it)
	{
		StatisticsItem anItem = *it;

		switch (anItem.type)
		{
		case arrowType:
		{
			QRect aRect = anItem.positionRect;
			QRect displayRect = QRect(aRect.left()*p_internalScaleFactor, aRect.top()*p_internalScaleFactor, aRect.width()*p_internalScaleFactor, aRect.height()*p_internalScaleFactor);

			int x, y;

			// start vector at center of the block
			x = displayRect.left() + displayRect.width() / 2;
			y = displayRect.top() + displayRect.height() / 2;

			QPoint startPoint = QPoint(x, y);

			float vx = anItem.vector[0];
			float vy = anItem.vector[1];

			QPoint arrowBase = QPoint(x + p_internalScaleFactor*vx, y + p_internalScaleFactor*vy);
			QColor arrowColor = anItem.color;
			//arrowColor.setAlpha( arrowColor.alpha()*((float)statsType.alphaFactor / 100.0) );

			QPen arrowPen(arrowColor);
			painter.setPen(arrowPen);
			painter.drawLine(startPoint, arrowBase);

			if (vx == 0 && vy == 0)
			{
				// nothing to draw...
			}
			else
			{
				// draw an arrow
				float nx, ny;

				// TODO: scale arrow head with
				float a = p_internalScaleFactor * 4;    // length of arrow
				float b = p_internalScaleFactor * 2;    // base width of arrow

				float n_abs = sqrtf(vx*vx + vy*vy);
				float vxf = (float)vx / n_abs;
				float vyf = (float)vy / n_abs;

				QPoint arrowTip = arrowBase + QPoint(vxf*a + 0.5, vyf*a + 0.5);

				// arrow head right
				rotateVector((float)-M_PI_2, -vx, -vy, nx, ny);
				QPoint offsetRight = QPoint(nx*b + 0.5, ny*b + 0.5);
				QPoint arrowHeadRight = arrowBase + offsetRight;

				// arrow head left
				rotateVector((float)M_PI_2, -vx, -vy, nx, ny);
				QPoint offsetLeft = QPoint(nx*b + 0.5, ny*b + 0.5);
				QPoint arrowHeadLeft = arrowBase + offsetLeft;

				// draw arrow head
				QPoint points[3] = { arrowTip, arrowHeadRight, arrowHeadLeft };
				painter.setBrush(arrowColor);
				painter.drawPolygon(points, 3);
			}

			break;
		}
		case blockType:
		{
			//draw a rectangle
			QColor rectColor = anItem.color;
			rectColor.setAlpha(rectColor.alpha()*((float)statsType.alphaFactor / 100.0));
			painter.setBrush(rectColor);

			QRect aRect = anItem.positionRect;
			QRect displayRect = QRect(aRect.left()*p_internalScaleFactor, aRect.top()*p_internalScaleFactor, aRect.width()*p_internalScaleFactor, aRect.height()*p_internalScaleFactor);

			painter.fillRect(displayRect, rectColor);

			break;
		}
		}

		// optionally, draw a grid around the region
		if (statsType.renderGrid) {
			//draw a rectangle
			QColor gridColor = anItem.gridColor;
			QPen gridPen(gridColor);
			gridPen.setWidth(1);
			painter.setPen(gridPen);
			painter.setBrush(QBrush(QColor(Qt::color0), Qt::NoBrush));  // no fill color

			QRect aRect = anItem.positionRect;
			QRect displayRect = QRect(aRect.left()*p_internalScaleFactor, aRect.top()*p_internalScaleFactor, aRect.width()*p_internalScaleFactor, aRect.height()*p_internalScaleFactor);

			painter.drawRect(displayRect);
		}
	}
}
Example #2
0
/*!
  Draw a color bar into a rectangle

  \param painter Painter
  \param colorMap Color map
  \param interval Value range
  \param scaleMap Scale map
  \param orientation Orientation
  \param rect Traget rectangle
*/
void QwtPainter::drawColorBar( QPainter *painter,
        const QwtColorMap &colorMap, const QwtInterval &interval,
        const QwtScaleMap &scaleMap, Qt::Orientation orientation,
        const QRectF &rect )
{
    QVector<QRgb> colorTable;
    if ( colorMap.format() == QwtColorMap::Indexed )
        colorTable = colorMap.colorTable256();

    QColor c;

    const QRect devRect = rect.toAlignedRect();

    /*
      We paint to a pixmap first to have something scalable for printing
      ( f.e. in a Pdf document )
     */

    QPixmap pixmap( devRect.size() );
    pixmap.fill( Qt::transparent );

    QPainter pmPainter( &pixmap );
    pmPainter.translate( -devRect.x(), -devRect.y() );

    if ( orientation == Qt::Horizontal )
    {
        QwtScaleMap sMap = scaleMap;
        sMap.setPaintInterval( rect.left(), rect.right() );

        for ( int x = devRect.left(); x <= devRect.right(); x++ )
        {
            const double value = sMap.invTransform( x );

            if ( colorMap.format() == QwtColorMap::RGB )
                c.setRgba( colorMap.rgb( interval, value ) );
            else
                c = colorTable[colorMap.colorIndex( 256, interval, value )];

            pmPainter.setPen( c );
            pmPainter.drawLine( x, devRect.top(), x, devRect.bottom() );
        }
    }
    else // Vertical
    {
        QwtScaleMap sMap = scaleMap;
        sMap.setPaintInterval( rect.bottom(), rect.top() );

        for ( int y = devRect.top(); y <= devRect.bottom(); y++ )
        {
            const double value = sMap.invTransform( y );

            if ( colorMap.format() == QwtColorMap::RGB )
                c.setRgba( colorMap.rgb( interval, value ) );
            else
                c = colorTable[colorMap.colorIndex( 256, interval, value )];

            pmPainter.setPen( c );
            pmPainter.drawLine( devRect.left(), y, devRect.right(), y );
        }
    }
    pmPainter.end();

    drawPixmap( painter, rect, pixmap );
}
Example #3
0
void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *option,
                                 QPainter *painter, const QWidget *widget) const
{
    if (!panelWidget(widget))
        return QProxyStyle::drawControl(element, option, painter, widget);

    switch (element) {
    case CE_Splitter:
        painter->fillRect(option->rect, StyleHelper::borderColor());
        break;

    case CE_TabBarTabShape:
        // Most styles draw a single dark outline. This looks rather ugly when combined with our
        // single pixel dark separator so we adjust the first tab to compensate for this

        if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(option)) {
            QStyleOptionTabV3 adjustedTab = *tab;
            if (tab->cornerWidgets == QStyleOptionTab::NoCornerWidgets && (
                    tab->position == QStyleOptionTab::Beginning ||
                    tab->position == QStyleOptionTab::OnlyOneTab))
            {
                if (option->direction == Qt::LeftToRight)
                    adjustedTab.rect = adjustedTab.rect.adjusted(-1, 0, 0, 0);
                else
                    adjustedTab.rect = adjustedTab.rect.adjusted(0, 0, 1 ,0);
            }
            QProxyStyle::drawControl(element, &adjustedTab, painter, widget);
            return;
        }
        break;

    case CE_MenuBarItem:
        painter->save();
        if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
            QColor highlightOutline = StyleHelper::borderColor().lighter(120);
            bool act = mbi->state & State_Sunken;
            bool dis = !(mbi->state & State_Enabled);
            StyleHelper::menuGradient(painter, option->rect, option->rect);
            QStyleOptionMenuItem item = *mbi;
            item.rect = mbi->rect;
            QPalette pal = mbi->palette;
            pal.setBrush(QPalette::ButtonText, dis ? Qt::gray : Qt::black);
            item.palette = pal;
            QCommonStyle::drawControl(element, &item, painter, widget);
            QRect r = option->rect;

            if (act) {
                // Fill|
                QColor baseColor = StyleHelper::baseColor();
                QLinearGradient grad(option->rect.topLeft(), option->rect.bottomLeft());
                grad.setColorAt(0, baseColor.lighter(120));
                grad.setColorAt(1, baseColor.lighter(130));
                painter->fillRect(option->rect.adjusted(1, 1, -1, 0), grad);

                // Outline
                painter->setPen(QPen(highlightOutline, 0));
                painter->drawLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom()));
                painter->drawLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom()));
                painter->drawLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()));
                highlightOutline.setAlpha(60);
                painter->setPen(QPen(highlightOutline, 0));
                painter->drawPoint(r.topLeft());
                painter->drawPoint(r.topRight());

                QPalette pal = mbi->palette;
                uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
                if (!styleHint(SH_UnderlineShortcut, mbi, widget))
                    alignment |= Qt::TextHideMnemonic;
                pal.setBrush(QPalette::Text, dis ? Qt::gray : QColor(0, 0, 0, 60));
                drawItemText(painter, item.rect.translated(0, 1), alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text);
                pal.setBrush(QPalette::Text, dis ? Qt::gray : Qt::white);
                drawItemText(painter, item.rect, alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text);
            }
        }
        painter->restore();
        break;

    case CE_ComboBoxLabel:
        if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
            if (panelWidget(widget)) {
                painter->save();
                QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
                QPalette customPal = cb->palette;
                bool drawIcon = !(widget && widget->property("hideicon").toBool());

                if (!cb->currentIcon.isNull() && drawIcon) {
                    QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
                                                                 : QIcon::Disabled;
                    QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
                    QRect iconRect(editRect);
                    iconRect.setWidth(cb->iconSize.width() + 4);
                    iconRect = alignedRect(cb->direction,
                                           Qt::AlignLeft | Qt::AlignVCenter,
                                           iconRect.size(), editRect);
                    if (cb->editable)
                        painter->fillRect(iconRect, customPal.brush(QPalette::Base));
                    drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);

                    if (cb->direction == Qt::RightToLeft)
                        editRect.translate(-4 - cb->iconSize.width(), 0);
                    else
                        editRect.translate(cb->iconSize.width() + 4, 0);

                    // Reserve some space for the down-arrow
                    editRect.adjust(0, 0, -13, 0);
                }

                QLatin1Char asterisk('*');
                int elideWidth = editRect.width();

                bool notElideAsterisk = widget && widget->property("notelideasterisk").toBool()
                                        && cb->currentText.endsWith(asterisk)
                                        && option->fontMetrics.width(cb->currentText) > elideWidth;

                QString text;
                if (notElideAsterisk) {
                    elideWidth -= option->fontMetrics.width(asterisk);
                    text = asterisk;
                }
                text.prepend(option->fontMetrics.elidedText(cb->currentText, Qt::ElideRight, elideWidth));

                if ((option->state & State_Enabled)) {
                    painter->setPen(QColor(0, 0, 0, 70));
                    painter->drawText(editRect.adjusted(1, 0, -1, 0), Qt::AlignLeft | Qt::AlignVCenter, text);
                } else {
                    painter->setOpacity(0.8);
                }
                painter->setPen(StyleHelper::panelTextColor());
                painter->drawText(editRect.adjusted(1, 0, -1, 0), Qt::AlignLeft | Qt::AlignVCenter, text);

                painter->restore();
            } else {
                QProxyStyle::drawControl(element, option, painter, widget);
            }
        }
        break;

    case CE_SizeGrip: {
            painter->save();
            QColor dark = Qt::white;
            dark.setAlphaF(0.1);
            int x, y, w, h;
            option->rect.getRect(&x, &y, &w, &h);
            int sw = qMin(h, w);
            if (h > w)
                painter->translate(0, h - w);
            else
                painter->translate(w - h, 0);
            int sx = x;
            int sy = y;
            int s = 4;
            painter->setPen(dark);
            if (option->direction == Qt::RightToLeft) {
                sx = x + sw;
                for (int i = 0; i < 4; ++i) {
                    painter->drawLine(x, sy, sx, sw);
                    sx -= s;
                    sy += s;
                }
            } else {
                for (int i = 0; i < 4; ++i) {
                    painter->drawLine(sx, sw, sw, sy);
                    sx += s;
                    sy += s;
                }
            }
            painter->restore();
        }
        break;

    case CE_MenuBarEmptyArea: {
            StyleHelper::menuGradient(painter, option->rect, option->rect);
            painter->save();
            painter->setPen(StyleHelper::borderColor());
            painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
            painter->restore();
        }
        break;

    case CE_ToolBar:
        {
            QRect rect = option->rect;
            bool horizontal = option->state & State_Horizontal;
            rect = option->rect;

            // Map offset for global window gradient
            QPoint offset = widget->window()->mapToGlobal(option->rect.topLeft()) -
                            widget->mapToGlobal(option->rect.topLeft());
            QRect gradientSpan;
            if (widget)
                gradientSpan = QRect(offset, widget->window()->size());

            bool drawLightColored = lightColored(widget);
            if (horizontal)
                StyleHelper::horizontalGradient(painter, gradientSpan, rect, drawLightColored);
            else
                StyleHelper::verticalGradient(painter, gradientSpan, rect, drawLightColored);

            if (!drawLightColored)
                painter->setPen(StyleHelper::borderColor());
            else
                painter->setPen(QColor(0x888888));

            if (horizontal) {
                // Note: This is a hack to determine if the
                // toolbar should draw the top or bottom outline
                // (needed for the find toolbar for instance)
                QColor lighter(StyleHelper::sidebarHighlight());
                if (drawLightColored)
                    lighter = QColor(255, 255, 255, 180);
                if (widget && widget->property("topBorder").toBool()) {
                    painter->drawLine(rect.topLeft(), rect.topRight());
                    painter->setPen(lighter);
                    painter->drawLine(rect.topLeft() + QPoint(0, 1), rect.topRight() + QPoint(0, 1));
                } else {
                    painter->drawLine(rect.bottomLeft(), rect.bottomRight());
                    painter->setPen(lighter);
                    painter->drawLine(rect.topLeft(), rect.topRight());
                }
            } else {
                painter->drawLine(rect.topLeft(), rect.bottomLeft());
                painter->drawLine(rect.topRight(), rect.bottomRight());
            }
        }
        break;

#if defined(Q_OS_MAC)
    case CE_ToolButtonLabel:
        if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(option)) {
            QStyleOptionToolButton myTb = *tb;
            myTb.state &= ~State_AutoRaise;

            QRect cr = tb->rect;
            bool needText = false;
            int alignment = 0;
            bool down = tb->state & (State_Sunken | State_On);
            // The down state is special for QToolButtons in a toolbar on the Mac
            // The text is a bit bolder and gets a drop shadow and the icons are also darkened.
            // This doesn't really fit into any particular case in QIcon, so we
            // do the majority of the work ourselves.
            if (!(tb->features & QStyleOptionToolButton::Arrow)) {
                Qt::ToolButtonStyle tbstyle = tb->toolButtonStyle;
                if (tb->icon.isNull() && !tb->text.isEmpty())
                    tbstyle = Qt::ToolButtonTextOnly;

                switch (tbstyle) {
                case Qt::ToolButtonTextOnly: {
                    needText = true;
                    alignment = Qt::AlignCenter;
                    break; }
                case Qt::ToolButtonIconOnly:
                case Qt::ToolButtonTextBesideIcon:
                case Qt::ToolButtonTextUnderIcon: {
                    QRect pr = cr;
                    QIcon::Mode iconMode = (tb->state & State_Enabled) ? QIcon::Normal
                                                                       : QIcon::Disabled;
                    QIcon::State iconState = (tb->state & State_On) ? QIcon::On
                                                                    : QIcon::Off;
                    QPixmap pixmap = tb->icon.pixmap(tb->rect.size().boundedTo(tb->iconSize), iconMode, iconState);

                    // Draw the text if it's needed.
                    if (tb->toolButtonStyle != Qt::ToolButtonIconOnly) {
                        needText = true;
                        if (tb->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
                            QMainWindow *mw = widget ? qobject_cast<QMainWindow *>(widget->window()) : 0;
                            if (mw && mw->unifiedTitleAndToolBarOnMac()) {
                                pr.setHeight(pixmap.size().height() / pixmap.devicePixelRatio());
                                cr.adjust(0, pr.bottom() + 1, 0, 1);
                            } else {
                                pr.setHeight(pixmap.size().height() / pixmap.devicePixelRatio() + 6);
                                cr.adjust(0, pr.bottom(), 0, -3);
                            }
                            alignment |= Qt::AlignCenter;
                        } else {
                            pr.setWidth(pixmap.width() / pixmap.devicePixelRatio() + 8);
                            cr.adjust(pr.right(), 0, 0, 0);
                            alignment |= Qt::AlignLeft | Qt::AlignVCenter;
                        }
                    }

                    proxy()->drawItemPixmap(painter, pr, Qt::AlignCenter, pixmap);
                    break; }
                default:
                    Q_ASSERT(false);
                    break;
                }

                if (needText) {
                    QPalette pal = tb->palette;
                    QPalette::ColorRole role = QPalette::WindowText;
                    if (!proxy()->styleHint(SH_UnderlineShortcut, tb, widget))
                        alignment |= Qt::TextHideMnemonic;
                    if (tbstyle == Qt::ToolButtonTextOnly || (tbstyle != Qt::ToolButtonTextOnly && !down)) {
                        painter->drawText(cr, alignment, tb->text);
                        if (down && tbstyle == Qt::ToolButtonTextOnly) {
                            pal = QApplication::palette("QMenu");
                            pal.setCurrentColorGroup(tb->palette.currentColorGroup());
                            role = QPalette::HighlightedText;
                        }
                    }
                    proxy()->drawItemText(painter, cr, alignment, pal,
                                          tb->state & State_Enabled, tb->text, role);
                }
            } else {
                QProxyStyle::drawControl(element, option, painter, widget);
            }
        }
        break;
#endif

    default:
        QProxyStyle::drawControl(element, option, painter, widget);
        break;
    }
}
Example #4
0
void ListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QRect r = option.rect;

    //Color: #C4C4C4
    QPen linePen(QColor::fromRgb(211, 211, 211), 2, Qt::SolidLine);

    //Color: #005A83
    QPen lineMarkedPen(QColor::fromRgb(0, 90, 131), 1, Qt::SolidLine);

    //Color: #333
    QPen fontPen(QColor::fromRgb(51, 51, 51), 1, Qt::SolidLine);

    //Color: #fff
    QPen fontMarkedPen(Qt::white, 1, Qt::SolidLine);

    //BORDER
    painter->setPen(linePen);
    painter->drawLine(r.topLeft(), r.topRight());
    painter->drawLine(r.topRight(), r.bottomRight());
    painter->drawLine(r.bottomLeft(), r.bottomRight());
    painter->drawLine(r.topLeft(), r.bottomLeft());

    if(option.state & QStyle::State_Selected)
    {
        QLinearGradient gradientSelected(r.left(), r.top(), r.left(), r.height() + r.top());
        gradientSelected.setColorAt(0.0, QColor::fromRgb(119, 213, 247));
        gradientSelected.setColorAt(0.9, QColor::fromRgb(27, 134, 183));
        gradientSelected.setColorAt(1.0, QColor::fromRgb(0, 120, 174));
        painter->setBrush(gradientSelected);
        painter->drawRect(r);

        //BORDER
        painter->setPen(lineMarkedPen);
        painter->drawLine(r.topLeft(), r.topRight());
        painter->drawLine(r.topRight(), r.bottomRight());
        painter->drawLine(r.bottomLeft(), r.bottomRight());
        painter->drawLine(r.topLeft(), r.bottomLeft());

        painter->setPen(fontMarkedPen);
    }
    else
    {
        //BACKGROUND
        //ALTERNATING COLORS
        painter->setBrush((index.row() % 2) ? Qt::white : QColor(252, 252, 252));
        painter->drawRect(r);

        //BORDER
        painter->setPen(linePen);
        painter->drawLine(r.topLeft(), r.topRight());
        painter->drawLine(r.topRight(), r.bottomRight());
        painter->drawLine(r.bottomLeft(), r.bottomRight());
        painter->drawLine(r.topLeft(), r.bottomLeft());

        painter->setPen(fontPen);
    }

    //GET TITLE, DESCRIPTION AND ICON
    QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
    QString title       = index.data(Qt::DisplayRole).toString();
    QString description = index.data(CP_DESC_ROLE).toString();

    int imageSpace = 10;
    if(!ic.isNull())
    {
        //ICON
        r = option.rect.adjusted(5, 10, -10, -10);
        ic.paint(painter, r, Qt::AlignVCenter | Qt::AlignLeft);
        imageSpace = 80;
    }

    //TITLE
    r = option.rect.adjusted(imageSpace, 0, -10, -30);
    painter->setFont(QFont("Lucida Grande", PGEDefaultFontSize + 2, QFont::Bold));
    painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom | Qt::AlignLeft, title, &r);

    //DESCRIPTION
    r = option.rect.adjusted(imageSpace, 30, -10, 30);
    painter->setFont(QFont("Lucida Grande", PGEDefaultFontSize, QFont::Normal));
    painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r);
}
Example #5
0
// -------------------------------------------------------------------------
void ctkTreeComboBox::resizePopup()
{
  // copied from QComboBox.cpp
  Q_D(ctkTreeComboBox);

  QStyle * const style = this->style();
  QWidget* container = qobject_cast<QWidget*>(this->view()->parent());

  QStyleOptionComboBox opt;
  this->initStyleOption(&opt);
  QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
                                       QStyle::SC_ComboBoxListBoxPopup, this));
  QRect screen = QApplication::desktop()->availableGeometry(
    QApplication::desktop()->screenNumber(this));
  QPoint below = this->mapToGlobal(listRect.bottomLeft());
  int belowHeight = screen.bottom() - below.y();
  QPoint above = this->mapToGlobal(listRect.topLeft());
  int aboveHeight = above.y() - screen.y();
  bool boundToScreen = !this->window()->testAttribute(Qt::WA_DontShowOnScreen);

  const bool usePopup = style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this);
    {
    int listHeight = 0;
    int count = 0;
    QStack<QModelIndex> toCheck;
    toCheck.push(this->view()->rootIndex());
#ifndef QT_NO_TREEVIEW
    QTreeView *treeView = qobject_cast<QTreeView*>(this->view());
    if (treeView && treeView->header() && !treeView->header()->isHidden())
      listHeight += treeView->header()->height();
#endif
    while (!toCheck.isEmpty())
      {
      QModelIndex parent = toCheck.pop();
      for (int i = 0; i < this->model()->rowCount(parent); ++i)
        {
        QModelIndex idx = this->model()->index(i, this->modelColumn(), parent);
        if (!idx.isValid())
          {
          continue;
          }
        listHeight += this->view()->visualRect(idx).height(); /* + container->spacing() */;
#ifndef QT_NO_TREEVIEW
        if (this->model()->hasChildren(idx) && treeView && treeView->isExpanded(idx))
          {
          toCheck.push(idx);
          }
#endif
        ++count;
        if (!usePopup && count > this->maxVisibleItems())
          {
          toCheck.clear();
          break;
          }
        }
      }
    listRect.setHeight(listHeight);
    }
      {
      // add the spacing for the grid on the top and the bottom;
      int heightMargin = 0;//2*container->spacing();

      // add the frame of the container
      int marginTop, marginBottom;
      container->getContentsMargins(0, &marginTop, 0, &marginBottom);
      heightMargin += marginTop + marginBottom;

      //add the frame of the view
      this->view()->getContentsMargins(0, &marginTop, 0, &marginBottom);
      //marginTop += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->top;
      //marginBottom += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->bottom;
      heightMargin += marginTop + marginBottom;

      listRect.setHeight(listRect.height() + heightMargin);
      }

      // Add space for margin at top and bottom if the style wants it.
      if (usePopup)
        {
        listRect.setHeight(listRect.height() + style->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) * 2);
        }

      // Make sure the popup is wide enough to display its contents.
      if (usePopup)
        {
        const int diff = d->computeWidthHint() - this->width();
        if (diff > 0)
          {
          listRect.setWidth(listRect.width() + diff);
          }
        }

      //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
      container->layout()->activate();
      //takes account of the minimum/maximum size of the container
      listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                        .boundedTo(container->maximumSize()));

      // make sure the widget fits on screen
      if (boundToScreen)
        {
        if (listRect.width() > screen.width() )
          {
          listRect.setWidth(screen.width());
          }
        if (this->mapToGlobal(listRect.bottomRight()).x() > screen.right())
          {
          below.setX(screen.x() + screen.width() - listRect.width());
          above.setX(screen.x() + screen.width() - listRect.width());
          }
        if (this->mapToGlobal(listRect.topLeft()).x() < screen.x() )
          {
          below.setX(screen.x());
          above.setX(screen.x());
          }
        }

      if (usePopup)
        {
        // Position horizontally.
        listRect.moveLeft(above.x());

#ifndef Q_WS_S60
        // Position vertically so the curently selected item lines up
        // with the combo box.
        const QRect currentItemRect = this->view()->visualRect(this->view()->currentIndex());
        const int offset = listRect.top() - currentItemRect.top();
        listRect.moveTop(above.y() + offset - listRect.top());
#endif

      // Clamp the listRect height and vertical position so we don't expand outside the
      // available screen geometry.This may override the vertical position, but it is more
      // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
#ifdef Q_WS_S60
        //popup needs to be stretched with screen minimum dimension
        listRect.setHeight(qMin(screen.height(), screen.width()));
#else
        listRect.setHeight(height);
#endif

        if (boundToScreen)
          {
          if (listRect.top() < screen.top())
            {
            listRect.moveTop(screen.top());
            }
          if (listRect.bottom() > screen.bottom())
            {
            listRect.moveBottom(screen.bottom());
            }
          }
#ifdef Q_WS_S60
        if (screen.width() < screen.height())
          {
          // in portait, menu should be positioned above softkeys
          listRect.moveBottom(screen.bottom());
          }
        else
          {
          TRect staConTopRect = TRect();
          AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
          listRect.setWidth(listRect.height());
          //by default popup is centered on screen in landscape
          listRect.moveCenter(screen.center());
          if (staConTopRect.IsEmpty())
            {
            // landscape without stacon, menu should be at the right
            (opt.direction == Qt::LeftToRight) ? listRect.setRight(screen.right()) :
              listRect.setLeft(screen.left());
            }
          }
#endif
        }
      else if (!boundToScreen || listRect.height() <= belowHeight)
        {
        listRect.moveTopLeft(below);
        }
      else if (listRect.height() <= aboveHeight)
        {
        listRect.moveBottomLeft(above);
        }
      else if (belowHeight >= aboveHeight)
        {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
        }
      else
        {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
        }

#if QT_VERSION < QT_VERSION_CHECK(5,0,0) && !defined QT_NO_IM
      if (QInputContext *qic = this->inputContext())
        {
        qic->reset();
        }
#endif
      QScrollBar *sb = this->view()->horizontalScrollBar();
      Qt::ScrollBarPolicy policy = this->view()->horizontalScrollBarPolicy();
      bool needHorizontalScrollBar =
        (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
        && sb->minimum() < sb->maximum();
      if (needHorizontalScrollBar)
        {
        listRect.adjust(0, 0, 0, sb->height());
        }
      container->setGeometry(listRect);
}
Example #6
0
void ActivityActionCanvas::draw(QPainter & p) {
  if (! visible()) return;
  
  QRect r = rect();
  QBrush brsh = p.brush();
  QColor bckgrnd = p.backgroundColor();
  
  p.setBackgroundMode((used_color == UmlTransparent)
		      ? ::Qt::TransparentMode
		      : ::Qt::OpaqueMode);

  QColor co = color(used_color);
  
  p.setBackgroundColor(co);
  
  const ActivityActionData * data =
    (ActivityActionData *) browser_node->get_data();
  const int shadow = the_canvas()->shadow();
  int margin;
  FILE * fp = svg();

  if (fp != 0)
    fputs("<g>\n", fp);  
  
  switch (data->get_action_kind()) {
  case UmlAcceptEventAction:
    if (((AcceptEventAction *) data->get_action())->timeevent) {
      // don't draw shadow
      margin = (int) (21 * the_canvas()->zoom());
      
      int t = (r.y() + r.bottom() - margin)/2;
      
      p.setPen(::Qt::SolidLine);
      p.setBackgroundMode(::Qt::TransparentMode);
      p.drawLine(r.right() - margin, t, r.right() - 1, t);
      p.lineTo(r.right() - margin - 1, t + margin);
      p.lineTo(r.right() - 1, t + margin);
      p.lineTo(r.right() - margin - 1, t);

      if (fp != 0) {
	fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.right() - margin, t, r.right() - 1, t);
	fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.right() - 1, t, r.right() - margin - 1, t + margin);
	fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.right() - margin - 1, t + margin, r.right() - 1, t + margin);
	fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		" x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		r.right() - 1, t + margin, r.right() - margin - 1, t);
      }

      r.setWidth(r.width() - margin - 1);
      margin = (int) (3 * the_canvas()->zoom());
    }
    else {
      if ((used_color != UmlTransparent) && (shadow != 0)) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
      }
      
      margin = ((r.height() < r.width()) ? r.height() : r.width()) / 4;
      
      QPointArray a(6);
      
      a.setPoint(0, r.x(), r.y());
      a.setPoint(1, r.right(), r.y());
      a.setPoint(2, r.right(), r.bottom());
      a.setPoint(3, r.x(), r.bottom());
      a.setPoint(4, r.x() + margin, (r.y() + r.bottom())/2);
      a.setPoint(5, r.x(), r.y());
  
      if (used_color == UmlTransparent) {
	p.drawPolyline(a);

	if (fp != 0)
	  draw_poly(fp, a, UmlTransparent);
      }
      else {
	if (shadow != 0) {
	  QPointArray b(6);
	  
	  b.setPoint(0, r.x() + shadow, r.y() + shadow);
	  b.setPoint(1, r.right() + shadow, r.y() + shadow);
	  b.setPoint(2, r.right() + shadow, r.bottom() + shadow);
	  b.setPoint(3, r.x() + shadow, r.bottom() + shadow);
	  b.setPoint(4, r.x() + margin + shadow, (r.y() + r.bottom())/2 + shadow);
	  b.setPoint(5, r.x() + shadow, r.y() + shadow);
	  p.setBrush(::Qt::darkGray);
	  p.setPen(::Qt::NoPen);
	  p.drawPolygon(b, TRUE, 0, 5);
	  p.setPen(::Qt::SolidLine);

	  if (fp != 0)
	    draw_shadow(fp, b);
	}
	
	p.setBrush(co);
	p.drawPolygon(a, TRUE, 0, 5);

	if (fp != 0)
	  draw_poly(fp, a, used_color);
      }
      r.setLeft(r.left() + margin);
      margin = (int) (6 * the_canvas()->zoom());
    }
    break;
  case UmlSendSignalAction:
  case UmlBroadcastSignalAction:
    {
      if ((used_color != UmlTransparent) && (shadow != 0)) {
	r.setRight(r.right() - shadow);
	r.setBottom(r.bottom() - shadow);
      }
      
      margin = ((r.height() < r.width()) ? r.height() : r.width()) / 4;
      
      QPointArray a(6);
      
      a.setPoint(0, r.x(), r.y());
      a.setPoint(1, r.right() - margin, r.y());
      a.setPoint(2, r.right(), (r.y() + r.bottom())/2);
      a.setPoint(3, r.right() - margin, r.bottom());
      a.setPoint(4, r.x(), r.bottom());
      a.setPoint(5, r.x(), r.y());
  
      if (used_color == UmlTransparent) {
	p.drawPolyline(a);
	if (fp != 0)
	  draw_poly(fp, a, UmlTransparent);
      }
      else {
	if (shadow != 0) {
	  QPointArray b(6);
	  
	  b.setPoint(0, r.x() + shadow, r.y() + shadow);
	  b.setPoint(1, r.right() - margin + shadow, r.y() + shadow);
	  b.setPoint(2, r.right() + shadow, (r.y() + r.bottom())/2 + shadow);
	  b.setPoint(3, r.right() - margin + shadow, r.bottom() + shadow);
	  b.setPoint(4, r.x() + shadow, r.bottom() + shadow);
	  b.setPoint(5, r.x() + shadow, r.y() + shadow);
	  p.setBrush(::Qt::darkGray);
	  p.setPen(::Qt::NoPen);
	  p.drawPolygon(b, TRUE, 0, 5);
	  p.setPen(::Qt::SolidLine);

	  if (fp != 0)
	    draw_shadow(fp, b);
	}
      
	p.setBrush(co);
	p.drawPolygon(a, TRUE, 0, 5);

	if (fp != 0)
	  draw_poly(fp, a, used_color);
      }
      r.setWidth(r.width() - margin);
      margin = (int) (6 * the_canvas()->zoom());
    }
    break;
  default:      
    margin = (int) (9 * the_canvas()->zoom());
      
    if ((used_color != UmlTransparent) && (shadow != 0)) {
      r.setRight(r.right() - shadow);
      r.setBottom(r.bottom() - shadow);
      p.setPen(::Qt::NoPen);
      p.setBrush(::Qt::darkGray);
      p.drawRoundRect(r.left() + shadow, r.top() + shadow, r.width(), r.height());
      
      if (fp != 0)
	fprintf(fp, "\t<rect fill=\"#%06x\" stroke=\"none\" stroke-opacity=\"1\""
		" x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"10\" />\n",
		::Qt::darkGray.rgb()&0xffffff,
		r.left() + shadow, r.top() + shadow, r.width() - 1, r.height() - 1);

      p.setPen(::Qt::SolidLine);
    }
    
    p.setBrush(co);
    p.drawRoundRect(r);

    if (fp != 0)
      fprintf(fp, "\t<rect fill=\"%s\" stroke=\"black\" stroke-opacity=\"1\""
	      " x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" rx=\"10\" />\n",
	      svg_color(used_color),
	      r.left(), r.top(), r.width() - 1, r.height() - 1);
    
    if (data->get_action_kind() == UmlCallBehaviorAction) {
      BrowserNode * behavior =
	((CallBehaviorAction *) data->get_action())->behavior;
      
      if ((behavior != 0) && (behavior->get_type() == UmlActivity)) {
	int l = (int) (6 * the_canvas()->zoom());
	int lx = r.right() - margin - l;
	int ty = r.bottom() - margin - l;
	int mx = lx + l;
	int my = ty + l;
	int rx = mx + l;
	int by = my + l;
	
	p.drawLine(lx, my, rx, my);
	p.drawLine(mx, ty, mx, by);
	p.drawLine(lx, my, lx, by);
	p.drawLine(rx, my, rx, by);

	if (fp != 0) {
	  fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		  " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		  lx, my, rx, my);
	  fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		  " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		  mx, ty, mx, by);
	  fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		  " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		  lx, my, lx, by);
	  fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
		  " x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" />\n",
		  rx, my, rx, by);
	}
      }
    }
    break;
  }
  
  p.setFont(the_canvas()->get_font(UmlNormalFont));
  p.drawText(r.x() + margin,
	     r.y() + margin,
	     r.width() - margin - margin,
	     r.height() - margin - margin,
	     align, s);
  
  if (fp != 0) {
    fputs("</g>\n", fp);
    draw_text(r.x() + margin,
	      r.y() + margin,
	      r.width() - margin - margin,
	      r.height() - margin - margin,
	      align, s, p.font(), fp);
  }
  
  p.setBackgroundColor(bckgrnd);
  p.setBrush(brsh);
  
  if (selected())
    show_mark(p, rect());
}
Example #7
0
bool MainWindow::eventFilter(QObject *o, QEvent *e)
{
#ifdef WIN32
    if (o->inherits("QSizeGrip")){
        QSizeGrip *grip = static_cast<QSizeGrip*>(o);
        QMouseEvent *me;
        switch (e->type()){
        case QEvent::MouseButtonPress:
            me = static_cast<QMouseEvent*>(e);
            p = me->globalPos();
            s = grip->topLevelWidget()->size();
            return true;
        case QEvent::MouseMove:
            me = static_cast<QMouseEvent*>(e);
            if (me->state() != LeftButton)
                break;
            QWidget *tlw = grip->topLevelWidget();
            QRect rc = tlw->geometry();
            if (tlw->testWState(WState_ConfigPending))
                break;
            QPoint np(me->globalPos());
            int w = np.x() - p.x() + s.width();
            int h = np.y() - p.y() + s.height();
            if ( w < 1 )
                w = 1;
            if ( h < 1 )
                h = 1;
            QSize ms(tlw->minimumSizeHint());
            ms = ms.expandedTo(minimumSize());
            if (w < ms.width())
                w = ms.width();
            if (h < ms.height())
                h = ms.height();
            if (!(GetWindowLongA(tlw->winId(), GWL_EXSTYLE) & WS_EX_APPWINDOW)){
                int dc = GetSystemMetrics(SM_CYCAPTION);
                int ds = GetSystemMetrics(SM_CYSMCAPTION);
                tlw->setGeometry(rc.left(), rc.top() + dc - ds, w, h);
            }else{
                tlw->resize(w, h);
            }
            MSG msg;
            while (PeekMessage(&msg, winId(), WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
            return true;
        }
    }
    if (e->type() == QEvent::ChildInserted){
        QChildEvent *ce = static_cast<QChildEvent*>(e);
        if (ce->child()->inherits("QSizeGrip"))
            ce->child()->installEventFilter(this);
    }
#endif
    if (e->type() == QEvent::ChildRemoved){
        QChildEvent *ce = static_cast<QChildEvent*>(e);
        list<QWidget*>::iterator it;
        for (it = statusWidgets.begin(); it != statusWidgets.end(); ++it){
            if (*it == ce->child()){
                statusWidgets.erase(it);
                break;
            }
        }
        if (statusWidgets.size() == 0){
            statusBar()->hide();
            setGrip();
        }
    }
    return QMainWindow::eventFilter(o, e);
}
Example #8
0
KviMainWindow::KviMainWindow(QWidget * pParent)
    : KviTalMainWindow(pParent, "kvirc_frame")
{
	g_pMainWindow = this;
	setAttribute(Qt::WA_DeleteOnClose);
	setAutoFillBackground(false);
	setAttribute(Qt::WA_TranslucentBackground);
	//disable this flag that gets enabled by qt when using Qt::WA_TranslucentBackground
	setAttribute(Qt::WA_NoSystemBackground, false);
#if !(defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) || defined(COMPILE_KDE_SUPPORT))
	// Under windows, the icon is builtin; under kde, KApplication sets it for us
	// We try to avois this as much as possible, since it forces the use of the low-res 16x16 icon
	setWindowIcon(*(g_pIconManager->getSmallIcon(KviIconManager::KVIrc)));
#endif

	m_pWinList = new KviPointerList<KviWindow>;
	setWindowTitle(KVI_DEFAULT_FRAME_CAPTION);
	m_pWinList->setAutoDelete(false);

	m_pModuleExtensionToolBarList = new KviPointerList<KviMexToolBar>;
	m_pModuleExtensionToolBarList->setAutoDelete(false);

	m_pActiveContext = nullptr;

	m_pTrayIcon = nullptr;

	m_pSplitter = new QSplitter(Qt::Horizontal, this);
	m_pSplitter->setObjectName("main_frame_splitter");
	m_pSplitter->setChildrenCollapsible(false);

	setCentralWidget(m_pSplitter);

	setIconSize(KVI_OPTION_UINT(KviOption_uintToolBarIconSize));
	setButtonStyle(KVI_OPTION_UINT(KviOption_uintToolBarButtonStyle));

	m_pWindowStack = new KviWindowStack(m_pSplitter, "mdi_manager");

	// This theoretically had to exists before KviWindowStack (that uses enterSdiMode)
	m_pAccellerators = new KviPointerList<QShortcut>;
	m_pMenuBar = new KviMenuBar(this, "main_menu_bar");
	setMenuWidget(m_pMenuBar);
#ifndef COMPILE_ON_MAC
	m_pMenuBar->setVisible(KVI_OPTION_BOOL(KviOption_boolMenuBarVisible));
#endif

	if(KVI_OPTION_BOOL(KviOption_boolStatusBarVisible))
	{
		m_pStatusBar = new KviStatusBar(this);
		setStatusBar(m_pStatusBar);
		// torque: moved out of status bar constructor
		// because module init functions executed in load()
		// couldn't access the status bar via g_pMainWindow->mainStatusBar()
		// (assignment of m_pStatusBar happened after load() and
		// the init function)
		m_pStatusBar->load();
	}
	else
	{
		m_pStatusBar = nullptr;
	}

	m_pWindowList = nullptr;

	createWindowList();

	if((KVI_OPTION_RECT(KviOption_rectFrameGeometry).width() < 100) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).height() < 100) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).x() > g_pApp->desktop()->width()) || (KVI_OPTION_RECT(KviOption_rectFrameGeometry).y() > g_pApp->desktop()->height()))
	{
		// Try to find some reasonable defaults
		// prefer primary screen for first startup
		int primary_screen = g_pApp->desktop()->primaryScreen();
		QRect r = g_pApp->desktop()->screenGeometry(primary_screen);
		r.setLeft(r.left() + 10);
		r.setRight(r.right() - 100);
		r.setTop(r.top() + 10);
		r.setBottom(r.bottom() - 200);
		KVI_OPTION_RECT(KviOption_rectFrameGeometry) = r;
	}

	resize(KVI_OPTION_RECT(KviOption_rectFrameGeometry).width(),
	    KVI_OPTION_RECT(KviOption_rectFrameGeometry).height());
	move(KVI_OPTION_RECT(KviOption_rectFrameGeometry).x(),
	    KVI_OPTION_RECT(KviOption_rectFrameGeometry).y());

	if(KVI_OPTION_BOOL(KviOption_boolFrameIsMaximized))
		showMaximized();

	applyOptions();

	installAccelerators();
}
Example #9
0
void QmitkHistogram::drawBar(QPainter *painter,
                             Qt::Orientation, const QRect& rect) const
{
  painter->save();

  const QColor color(painter->pen().color());
#if QT_VERSION >= 0x040000
  const QRect r = rect.normalized();
#else
  const QRect r = rect.normalize();
#endif

  const int factor = 125;
  const QColor light(color.light(factor));
  const QColor dark(color.dark(factor));

  painter->setBrush(color);
  painter->setPen(Qt::NoPen);
  QwtPainter::drawRect(painter, r.x() + 1, r.y() + 1,
    r.width() - 2, r.height() - 2);
  painter->setBrush(Qt::NoBrush);

  painter->setPen(QPen(light, 2));
#if QT_VERSION >= 0x040000
  QwtPainter::drawLine(painter,
    r.left() + 1, r.top() + 2, r.right() + 1, r.top() + 2);
#else
  QwtPainter::drawLine(painter,
    r.left(), r.top() + 2, r.right() + 1, r.top() + 2);
#endif

  painter->setPen(QPen(dark, 2));
#if QT_VERSION >= 0x040000
  QwtPainter::drawLine(painter, 
    r.left() + 1, r.bottom(), r.right() + 1, r.bottom());
#else
  QwtPainter::drawLine(painter, 
    r.left(), r.bottom(), r.right() + 1, r.bottom());
#endif

  painter->setPen(QPen(light, 1));

#if QT_VERSION >= 0x040000
  QwtPainter::drawLine(painter, 
    r.left(), r.top() + 1, r.left(), r.bottom());
  QwtPainter::drawLine(painter,
    r.left() + 1, r.top() + 2, r.left() + 1, r.bottom() - 1);
#else
  QwtPainter::drawLine(painter, 
    r.left(), r.top() + 1, r.left(), r.bottom() + 1);
  QwtPainter::drawLine(painter,
    r.left() + 1, r.top() + 2, r.left() + 1, r.bottom());
#endif

  painter->setPen(QPen(dark, 1));

#if QT_VERSION >= 0x040000
  QwtPainter::drawLine(painter, 
    r.right() + 1, r.top() + 1, r.right() + 1, r.bottom());
  QwtPainter::drawLine(painter, 
    r.right(), r.top() + 2, r.right(), r.bottom() - 1);
#else
  QwtPainter::drawLine(painter, 
    r.right() + 1, r.top() + 1, r.right() + 1, r.bottom() + 1);
  QwtPainter::drawLine(painter, 
    r.right(), r.top() + 2, r.right(), r.bottom());
#endif

  painter->restore();
}
void QgsCollapsibleGroupBox::updateStyle()
{
  setUpdatesEnabled( false );

  // margin/offset defaults
  int marginLeft = 20;  // title margin for disclosure triangle
  int marginRight = 5;  // a little bit of space on the right, to match space on the left
  int offsetLeft = 0;   // offset for oxygen theme
  int offsetTop = 0;
  int offsetTop2 = 0;   // offset for triangle

  // calculate offset if frame overlaps triangle (oxygen theme)
  // using an offset of 6 pixels from frame border
  if ( QApplication::style()->objectName().toLower() == "oxygen" )
  {
    QStyleOptionGroupBox box;
    initStyleOption( &box );
    QRect rectFrame = style()->subControlRect( QStyle::CC_GroupBox, &box,
                      QStyle::SC_GroupBoxFrame, this );
    QRect rectCheckBox = style()->subControlRect( QStyle::CC_GroupBox, &box,
                         QStyle::SC_GroupBoxCheckBox, this );
    if ( rectFrame.left() <= 0 )
      offsetLeft = 6 + rectFrame.left();
    if ( rectFrame.top() <= 0 )
    {
      if ( isCheckable() )
      {
        // if is checkable align with checkbox
        offsetTop = ( rectCheckBox.height() / 2 ) -
                    ( mCollapseButton->height() / 2 ) + rectCheckBox.top();
        offsetTop2 = offsetTop + 1;
      }
      else
      {
        offsetTop = 6 + rectFrame.top();
        offsetTop2 = offsetTop;
      }
    }
  }

  QgsDebugMsg( QString( "groupbox: %1 style: %2 offset: left=%3 top=%4 top2=%5" ).arg(
                 objectName() ).arg( QApplication::style()->objectName() ).arg( offsetLeft ).arg( offsetTop ).arg( offsetTop2 ) );

  // customize style sheet for collapse/expand button and force left-aligned title
  // TODO: move to app stylesheet system, when appropriate
  QString ss;
  ss += "QgsCollapsibleGroupBox::title {";
  ss += "  subcontrol-origin: margin;";
  ss += "  subcontrol-position: top left;";
  ss += QString( "  margin-left: %1px;" ).arg( marginLeft );
  ss += QString( "  margin-right: %1px;" ).arg( marginRight );
  ss += QString( "  left: %1px;" ).arg( offsetLeft );
  ss += QString( "  top: %1px;" ).arg( offsetTop );
  ss += "}";
  setStyleSheet( ss );

  // clear toolbutton default background and border and apply offset
  QString ssd;
  ssd = QString( "QgsCollapsibleGroupBox > QToolButton#%1 {" ).arg( mCollapseButton->objectName() );
  ssd += "  background-color: rgba(255, 255, 255, 0); border: none;";
  ssd += "}";
  mCollapseButton->setStyleSheet( ssd );
  if ( offsetLeft != 0 || offsetTop2 != 0 )
    mCollapseButton->move( offsetLeft, offsetTop2 );

  setUpdatesEnabled( true );
}
Example #11
0
void BaseEditor::paintEvent(QPaintEvent *e)
{
    //copy from QPlainTextEditor
    QPainter painter(viewport());
    Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout()));

    QPointF offset(contentOffset());

    QRect er = e->rect();
    QRect viewportRect = viewport()->rect();

    bool editable = !isReadOnly();

    QTextBlock block = firstVisibleBlock();
    qreal maximumWidth = document()->documentLayout()->documentSize().width();

    //margin
    qreal lineX = 0;
    if (conf->isDisplayRightColumnMargin()) {
        // Don't use QFontMetricsF::averageCharWidth here, due to it returning
        // a fractional size even when this is not supported by the platform.
        lineX = QFontMetricsF(document()->defaultFont()).width(QLatin1Char('X')) * conf->getRightMarginColumn() + offset.x() + 4;

        if (lineX < viewportRect.width()) {
            const QBrush background = QBrush(QColor(239, 239, 239));
            painter.fillRect(QRectF(lineX, er.top(), viewportRect.width() - lineX, er.height()),
                             background);

            const QColor col = (palette().base().color().value() > 128) ? Qt::black : Qt::white;
            const QPen pen = painter.pen();
            painter.setPen(blendColors(background.isOpaque() ? background.color() : palette().base().color(),
                                       col, 32));
            painter.drawLine(QPointF(lineX, er.top()), QPointF(lineX, er.bottom()));
            painter.setPen(pen);
        }
    }

    // Set a brush origin so that the WaveUnderline knows where the wave started
    painter.setBrushOrigin(offset);

    // keep right margin clean from full-width selection
    int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
               - document()->documentMargin();
    er.setRight(qMin(er.right(), maxX));
    painter.setClipRect(er);


    QAbstractTextDocumentLayout::PaintContext context = getPaintContext();

    while (block.isValid()) {

        QRectF r = blockBoundingRect(block).translated(offset);
        QTextLayout *layout = block.layout();

        if (!block.isVisible()) {
            offset.ry() += r.height();
            block = block.next();
            continue;
        }

        if (r.bottom() >= er.top() && r.top() <= er.bottom()) {

            QTextBlockFormat blockFormat = block.blockFormat();

            QBrush bg = blockFormat.background();
            if (bg != Qt::NoBrush) {
                QRectF contentsRect = r;
                contentsRect.setWidth(qMax(r.width(), maximumWidth));
                fillBackground(&painter, contentsRect, bg);
            }


            QVector<QTextLayout::FormatRange> selections;
            int blpos = block.position();
            int bllen = block.length();
            for (int i = 0; i < context.selections.size(); ++i) {
                const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
                const int selStart = range.cursor.selectionStart() - blpos;
                const int selEnd = range.cursor.selectionEnd() - blpos;
                if (selStart < bllen && selEnd > 0
                    && selEnd > selStart) {
                    QTextLayout::FormatRange o;
                    o.start = selStart;
                    o.length = selEnd - selStart;
                    o.format = range.format;
                    selections.append(o);
                } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
                           && block.contains(range.cursor.position())) {
                    // for full width selections we don't require an actual selection, just
                    // a position to specify the line. that's more convenience in usage.
                    QTextLayout::FormatRange o;
                    QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
                    o.start = l.textStart();
                    o.length = l.textLength();
                    if (o.start + o.length == bllen - 1)
                        ++o.length; // include newline
                    o.format = range.format;
                    selections.append(o);
                }
            }

            bool drawCursor = ((editable || (textInteractionFlags() & Qt::TextSelectableByKeyboard))
                               && context.cursorPosition >= blpos
                               && context.cursorPosition < blpos + bllen);

            bool drawCursorAsBlock = drawCursor && overwriteMode() ;

            if (drawCursorAsBlock) {
                if (context.cursorPosition == blpos + bllen - 1) {
                    drawCursorAsBlock = false;
                } else {
                    QTextLayout::FormatRange o;
                    o.start = context.cursorPosition - blpos;
                    o.length = 1;
                    o.format.setForeground(palette().base());
                    o.format.setBackground(palette().text());
                    selections.append(o);
                }
            }


            layout->draw(&painter, offset, selections, er);
            if ((drawCursor && !drawCursorAsBlock)
                || (editable && context.cursorPosition < -1
                    && !layout->preeditAreaText().isEmpty())) {
                int cpos = context.cursorPosition;
                if (cpos < -1)
                    cpos = layout->preeditAreaPosition() - (cpos + 2);
                else
                    cpos -= blpos;
                layout->drawCursor(&painter, offset, cpos, cursorWidth());
            }
        }

        offset.ry() += r.height();
        if (offset.y() > viewportRect.height())
            break;
        block = block.next();
    }

    if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom()
        && (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) {
        painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background());
    }
}
void NextAvailabiliyStepViewer::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPen pen;
    // Draw hours & half hour
    pen.setColor(QColor("gray"));
    painter.setPen(pen);
    for(int i = 0; i < 7*24; ++i) {
        int y = i*60/scaleFactor;
        painter.drawLine(0, y, 50, y);
        painter.drawText(25, y + 20, QString::number(i%24).rightJustified(2, '0'));
    }
    for(int i = 0; i < 7*24*2; ++i) {
        int y = i*30/scaleFactor;
        painter.drawLine(0, y, 20, y);
        painter.drawLine(45, y, 50, y);
    }
    // Draw day limits && day name
    pen.setColor(QColor("darkblue"));
    painter.setPen(pen);
    for(int i = 0; i < 8; ++i) {
        int y = i*1440/scaleFactor;
        painter.drawLine(0, y, 200, y);
        painter.drawText(150, y + 40, QDate::shortDayName(i+1));
    }

    // Draw avails
    pen.setStyle(Qt::DotLine);
    painter.setPen(pen);
    for(int i = 0; i < avs.count(); ++i) {
        const QRect &r = avs.at(i);
        int top = r.top()/scaleFactor;
        QRect drawMe(0, top, r.width(), r.height()/scaleFactor);
        painter.fillRect(drawMe, QColor("yellow")); //QColor(220, 220, 220));
        painter.drawRect(drawMe);
        painter.drawText(5, top+10, QString::number(i));
    }
    pen.setStyle(Qt::SolidLine);

    // Draw appointemnts
    pen.setColor(QColor("black"));
    painter.setPen(pen);
    for(int i = 0; i < aps.count(); ++i) {
        const QRect &r = aps.at(i);
        int top = r.top()/scaleFactor;
        QRect drawMe(0, top, r.width(), r.height()/scaleFactor+1);
        painter.fillRect(drawMe, QColor("gray")); //QColor(220, 220, 220));
        painter.drawRect(drawMe);
//        painter.drawText(30, top+10, QString::number(i));
    }

    // Draw free
    for(int i = 0; i < free.count(); ++i) {
        const QRect &r = free.at(i);
        int top = r.top()/scaleFactor;
        QRect drawMe(55, top, r.width(), r.height()/scaleFactor+1);
        painter.fillRect(drawMe, QColor("red")); //QColor(220, 220, 220));
        painter.drawRect(drawMe);
    }

    // Draw now
    QRect now = NextAvailabiliyManager::dateToRect(QDateTime::currentDateTime(), 1);
    pen.setColor("black");
    painter.drawLine(100, now.top()/scaleFactor, 500, now.top()/scaleFactor);
}
/** Return the next available appointments by searching for
  - \e startSearch date time,
  - a duration of \e duration minutes
  - for the agenda \e calendar
  - limiting search to \e numberOfDates appointments
*/
QList<QDateTime> NextAvailabiliyManager::nextAvailableTime(const QDateTime &startSearch,
                                                           const int durationInMinutes,
                                                           const int calendarDurationInMinutes,
                                                           const QRect &nextAppointment,
                                                           const int numberOfDates)
{
    QList<QDateTime> toReturn;
    m_ReachedNextAppointment = false;
    m_NeedLaterThan = QDateTime();

    // Some checkings
    if (durationInMinutes <= 0)
        return toReturn;
    if (numberOfDates <= 0)
        return toReturn;
    if ((!nextAppointment.isNull()) && (rectToDateStart(nextAppointment) < startSearch)) {
        if (WarnDebugs)
            qWarning() << "NextApp < StartSearch" << rectToDateStart(nextAppointment) << startSearch;
        m_ReachedNextAppointment = true;
        QDateTime nextEnd = rectToDateEnd(nextAppointment);
        if (nextEnd > startSearch)
            m_NeedLaterThan = nextEnd;//, calendarDurationInMinutes;
        else
            m_NeedLaterThan = Utils::roundDateTime(startSearch, calendarDurationInMinutes);
        return toReturn;
    }

    // Here we can go on
    QDateTime start;
    start = Utils::roundDateTime(startSearch, calendarDurationInMinutes);

    if (WarnDebugs)
        qWarning() << "-------------------\nSTART" << start << "nextApp" << rectToDateStart(nextAppointment);

    // get the first event and make tests

    int nbFound = 0;
    int durationInSeconds = durationInMinutes * 60;
    // TODO: manage algorythm error here
    int limitComputation = 10000;//224640; // 10min, 6day a week, 12hours a day :: 1 full year == 12*6 *10 *6 *52 == 224640

    while (nbFound < numberOfDates) {
        --limitComputation;
        if (limitComputation <= 0)
            break;
        if (start.isNull())
            break;

        QRect testDate = dateToRect(start, durationInMinutes);

#if QT_VERSION < 0x050000
        if (WarnDebugs)
            qWarning() << "TEST" << testDate.intersect(nextAppointment).height();

        // rect does not intersect the next recorded appointment ? -> go next appointment
        while ((testDate.intersect(nextAppointment).height() < 1) || nextAppointment.isNull()) {

            if (WarnDebugs)
                qWarning() << "---\ntest" << testDate << "next" << nextAppointment << testDate.intersect(nextAppointment).height() << "topTest" << (nextAppointment.top() <= testDate.top());
#else
        if (WarnDebugs)
            qWarning() << "TEST" << testDate.intersected(nextAppointment).height();

        // rect does not intersect the next recorded appointment ? -> go next appointment
        while ((testDate.intersected(nextAppointment).height() < 1) || nextAppointment.isNull()) {

            if (WarnDebugs)
                qWarning() << "---\ntest" << testDate << "next" << nextAppointment << testDate.intersected(nextAppointment).height() << "topTest" << (nextAppointment.top() <= testDate.top());
#endif

            if (nbFound == numberOfDates) {
                return toReturn;
            }

            // rect in availabilities ?
            bool inAvail = isInAvailabilities(avs, testDate);

            if (inAvail) {
                // Add date
//                if (WarnNextAvailableTimeWarnings)
//                    qWarning() << "Adding" << start;
                toReturn << start;
                ++nbFound;
                // Add duration to start and/or go to beginning of next availability and cycle
                start = start.addSecs(durationInSeconds);
                testDate = dateToRect(start, durationInMinutes);
            } else {
                if (WarnDebugs)
                    qWarning() << "Not In Availabilities";
                // go to the next avail beginning
                int minutesToNextAvail = minutesToNextAvailability(avs, testDate);
                start = start.addSecs(minutesToNextAvail*60);// + testDate.height()*60);
                if (WarnDebugs)
                    qWarning() << "minToAv" << minutesToNextAvail << start << dateToRect(start, durationInMinutes);
                // did we go after the next appointment ? -> require new appointment
                if (!nextAppointment.isNull()) {
                    QDateTime nextStart = rectToDateStart(nextAppointment);
                    if (start > nextStart) {
                        if (WarnDebugs)
                            qWarning() << "start" << start << "nextApp" << nextStart;
                        break;
                    }
                }
                testDate = dateToRect(start, durationInMinutes);
            }
        }

        // requiere next appointment
        m_ReachedNextAppointment = true;
        QDateTime nextAppEnd = rectToDateEnd(nextAppointment);
        if (nextAppEnd > start)
            m_NeedLaterThan = nextAppEnd;
        else
            m_NeedLaterThan = start;
        return toReturn;
    }

    if (WarnDebugs)
        qWarning() << "No available time found";


    return toReturn;
}
Example #14
0
void poly()
{
    QWidget *d = QApplication::desktop();
    d->setBackgroundColor( white );		// white desktop

    const int maxpoints = 5;
    const int maxcurves = 8;
    static int xvel[maxpoints];
    static int yvel[maxpoints];
    int head = 0;
    int tail = -maxcurves + 2;
    QPointArray *a = new QPointArray[ maxcurves ];
    register QPointArray *p;
    QRect r = d->rect();			// desktop rectangle

    int i;
    for ( i=0; i<maxcurves; i++ )
	a[i].resize( maxpoints );
    p = &a[0];
    for ( i=0; i<maxpoints; i++ ) {		// setup first polygon points
	p->setPoint( i, (kindaRand()&0x7fff) % r.width(),
			(kindaRand()&0x7fff) % r.height() );
	xvel[i] = velocity(i);
	yvel[i] = velocity(i);
    }

    QPainter paint;
    paint.begin( d );				// start painting desktop

    for ( int ntimes=0; ntimes<2000; ntimes++ ) {
	paint.setBrush( QColor(kindaRand()%360, 180, 255, QColor::Hsv) );
	paint.drawPolygon( a[head] );
	if ( ++tail >= maxcurves )
	    tail = 0;

	int minx=r.left(), maxx=r.right();
	int miny=r.top(),  maxy=r.bottom();
	int x, y;
	p = &a[head];
	if ( ++head >= maxcurves )
	    head = 0;
	for ( i=0; i<maxpoints; i++ ) {		// calc new curve
	    p->point( i, &x, &y );
	    x += xvel[i];
	    y += yvel[i];
	    if ( x >= maxx ) {
		x = maxx - (x - maxx + 1);
		xvel[i] = -velocity(i);
	    }
	    if ( x <= minx ) {
		x = minx + (minx - x + 1);
		xvel[i] = velocity(i);
	    }
	    if ( y >= maxy ) {
		y = maxy - (y - maxy + 1);
		yvel[i] = -velocity(i);
	    }
	    if ( y <= miny ) {
		y = miny + (miny - y + 1);
		yvel[i] = velocity(i);
	    }
	    a[head].setPoint( i, x, y );
	}
    }
    paint.end();				// painting done
    delete[] a;
}
Example #15
0
bool MergeCommand::preProcessing()
{
    if (isColumnOrRowSelected()) {
        KMessageBox::information(0, i18n("Merging of columns or rows is not supported."));
        return false;
    }

    if (m_firstrun) {
        setText(name());

        // reduce the region to the region occupied by merged cells
        Region mergedCells;
        ConstIterator endOfList = constEnd();
        for (ConstIterator it = constBegin(); it != endOfList; ++it) {
            Element* element = *it;
            QRect range = element->rect();
            int right = range.right();
            int bottom = range.bottom();
            for (int row = range.top(); row <= bottom; ++row) {
                for (int col = range.left(); col <= right; ++col) {
                    Cell cell = Cell(m_sheet, col, row);
                    if (cell.doesMergeCells()) {
                        QRect rect(col, row, cell.mergedXCells() + 1, cell.mergedYCells() + 1);
                        mergedCells.add(rect);
                    }
                }
            }
        }

        if (m_merge) { // MergeCommand
            // we're in the manipulator's first execution
            // initialize the undo manipulator
            m_unmerger = new MergeCommand();
            if (!m_mergeHorizontal && !m_mergeVertical) {
                m_unmerger->setReverse(true);
            }
            m_unmerger->setSheet(m_sheet);
            m_unmerger->setRegisterUndo(false);
            m_unmerger->add(mergedCells);
        } else { // DissociateManipulator
            clear();
            add(mergedCells);
        }
    }

    if (m_merge) { // MergeCommand
        if (m_reverse) { // dissociate
        } else { // merge
            // Dissociate cells before merging the whole region.
            // For horizontal/vertical merging the cells stay
            // as they are. E.g. the region contains a merged cell
            // occupying two rows. Then the horizontal merge should
            // keep the height of two rows and extend the merging to the
            // region's width. In this case the unmerging is done while
            // processing each region element.
            if (!m_mergeHorizontal && !m_mergeVertical) {
                m_unmerger->redo();
            }
        }
    }
    // Clear the associated selection, if any. The merge/dissociate process will restore
    // selections. This ensures that the selection isn't broken after merging.
    if (m_selection) m_selection->Region::clear();

    return AbstractRegionCommand::preProcessing();
}
Example #16
0
BalloonMsg::BalloonMsg(void *param, const QString &_text, QStringList &btn, QWidget *parent, const QRect *rcParent,
                       bool bModal, bool bAutoHide, unsigned bwidth, const QString &box_msg, bool *bChecked)
        : QDialog(parent, "ballon", bModal,
                  (bAutoHide ? WType_Popup : WType_TopLevel | WStyle_StaysOnTop)
                  | WStyle_Customize | WStyle_NoBorderEx | WStyle_Tool | WDestructiveClose | WX11BypassWM)
{
    m_param = param;
    m_parent = parent;
    m_width = bwidth;
    m_bAutoHide = bAutoHide;
    m_bYes = false;
    m_bChecked = bChecked;
    bool bTailDown = true;
    setPalette(QToolTip::palette());
    text = _text;
    QFrame *frm = new QFrame(this);
    frm->setPalette(palette());
    QVBoxLayout *vlay = new QVBoxLayout(frm);
    vlay->setMargin(0);
    m_check = NULL;
    if (!box_msg.isEmpty()){
        m_check = new QCheckBox(box_msg, frm);
        vlay->addWidget(m_check);
        if (m_bChecked)
            m_check->setChecked(*m_bChecked);
    }
    QHBoxLayout *lay = new QHBoxLayout(vlay);
    lay->setSpacing(5);
    lay->addStretch();
    unsigned id = 0;
    bool bFirst = true;
    for (QStringList::Iterator it = btn.begin(); it != btn.end(); ++it, id++){
        BalloonButton *b = new BalloonButton(*it, frm, id);
        connect(b, SIGNAL(action(int)), this, SLOT(action(int)));
        lay->addWidget(b);
        if (bFirst){
            b->setDefault(true);
            bFirst = false;
        }
    }
    setButtonsPict(this);
    lay->addStretch();
    int wndWidth = frm->minimumSizeHint().width();
    int hButton  = frm->minimumSizeHint().height();

    int txtWidth = bwidth;
    QRect rc;
    if (rcParent){
        rc = *rcParent;
    }else{
        QPoint p = parent->mapToGlobal(parent->rect().topLeft());
        rc = QRect(p.x(), p.y(), parent->width(), parent->height());
    }
    if (rc.width() > txtWidth) txtWidth = rc.width();

    QSimpleRichText richText(_text, font(), "", QStyleSheet::defaultSheet(), QMimeSourceFactory::defaultFactory(), -1, Qt::blue, false);
    richText.setWidth(wndWidth);
    richText.adjustSize();
    QSize s(richText.widthUsed(), richText.height());
    QSize sMin = frm->minimumSizeHint();
    if (s.width() < sMin.width())
        s.setWidth(sMin.width());
    int BALLOON_SHADOW = BALLOON_SHADOW_DEF;
#ifdef WIN32
    /* FIXME */
    /*    if ((GetClassLong(winId(), GCL_STYLE) & CS_DROPSHADOW) && style().inherits("QWindowsXPStyle"))
            BALLOON_SHADOW = 0; */
#endif
    resize(s.width() + BALLOON_R * 2 + BALLOON_SHADOW,
           s.height() + BALLOON_R * 2 + BALLOON_TAIL + BALLOON_SHADOW + hButton + BALLOON_MARGIN);
    mask = QBitmap(width(), height());
    int w = width() - BALLOON_SHADOW;
    int tailX = w / 2;
    int posX = rc.left() + rc.width() / 2 + BALLOON_TAIL_WIDTH - tailX;
    if (posX <= 0) posX = 1;
    QRect rcScreen = screenGeometry();
    if (posX + width() >= rcScreen.width())
        posX = rcScreen.width() - 1 - width();
    int tx = posX + tailX - BALLOON_TAIL_WIDTH;
    if (tx < rc.left()) tx = rc.left();
    if (tx > rc.left() + rc.width()) tx = rc.left() + rc.width();
    tailX = tx + BALLOON_TAIL_WIDTH - posX;
    if (tailX < BALLOON_R) tailX = BALLOON_R;
    if (tailX > width() - BALLOON_R - BALLOON_TAIL_WIDTH) tailX = width() - BALLOON_R - BALLOON_TAIL_WIDTH;
    if (rc.top() <= height() + 2){
        bTailDown = false;
        move(posX, rc.top() + rc.height() + 1);
    }else{
        move(posX, rc.top() - height() - 1);
    }
    int pos = 0;
    int h = height() - BALLOON_SHADOW - BALLOON_TAIL;
    if (!bTailDown) pos += BALLOON_TAIL;
    textRect.setRect(BALLOON_R, pos + BALLOON_R, w - BALLOON_R * 2, h);
    frm->resize(s.width(), hButton);
    frm->move(BALLOON_R, pos + h - BALLOON_R - hButton);
    QPainter p;
    p.begin(&mask);
#ifdef WIN32
    QColor bg(255, 255, 255);
    QColor fg(0, 0, 0);
#else
    QColor bg(0, 0, 0);
    QColor fg(255, 255, 255);
#endif
    p.fillRect(0, 0, width(), height(), bg);
    p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, fg);
    p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, fg);
    p.fillRect(BALLOON_SHADOW, pos + BALLOON_R + BALLOON_SHADOW, w, h - BALLOON_R * 2, fg);
    p.fillRect(BALLOON_R + BALLOON_SHADOW, pos + BALLOON_SHADOW, w - BALLOON_R * 2, h, fg);
    p.setBrush(fg);
    p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2 + BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(BALLOON_SHADOW, pos + h - BALLOON_R * 2 + BALLOON_SHADOW, BALLOON_R * 2, BALLOON_R * 2);
    QPointArray arr(3);
    arr.setPoint(0, tailX, bTailDown ? h : pos);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h : pos);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0);
    p.drawPolygon(arr);
    arr.setPoint(0, tailX + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH + BALLOON_SHADOW, (bTailDown ? h : pos) + BALLOON_SHADOW);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH + BALLOON_SHADOW, bTailDown ? height() : BALLOON_SHADOW);
    p.drawPolygon(arr);
    p.end();
    setMask(mask);
    qApp->syncX();
    QPixmap pict = QPixmap::grabWindow(QApplication::desktop()->winId(), x(), y(), width(), height());
    intensity(pict, -0.50f);
    p.begin(&pict);
    p.setBrush(colorGroup().background());
    p.drawEllipse(0, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(w - BALLOON_R * 2, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    p.drawEllipse(0, pos + h - BALLOON_R * 2, BALLOON_R * 2, BALLOON_R * 2);
    arr.setPoint(0, tailX, bTailDown ? h - 1 : pos + 1);
    arr.setPoint(1, tailX + BALLOON_TAIL_WIDTH, bTailDown ? h - 1 : pos + 1);
    arr.setPoint(2, tailX - BALLOON_TAIL_WIDTH, bTailDown ? height() - BALLOON_SHADOW : 0);
    p.drawPolygon(arr);
    p.fillRect(0, pos + BALLOON_R, w, h - BALLOON_R * 2, colorGroup().background());
    p.fillRect(BALLOON_R, pos, w - BALLOON_R * 2, h, colorGroup().background());
    p.drawLine(0, pos + BALLOON_R, 0, pos + h - BALLOON_R);
    p.drawLine(w - 1, pos + BALLOON_R, w - 1, pos + h - BALLOON_R);
    if (bTailDown){
        p.drawLine(BALLOON_R, 0, w - BALLOON_R, 0);
        p.drawLine(BALLOON_R, h - 1, tailX, h - 1);
        p.drawLine(tailX + BALLOON_TAIL_WIDTH, h - 1, w - BALLOON_R, h - 1);
    }else{
        p.drawLine(BALLOON_R, pos + h - 1, w - BALLOON_R, pos + h - 1);
        p.drawLine(BALLOON_R, pos, tailX, pos);
        p.drawLine(tailX + BALLOON_TAIL_WIDTH, pos, w - BALLOON_R, pos);
    }
    p.end();
    setBackgroundPixmap(pict);
    setAutoMask(true);
    if (!bAutoHide)
        setFocusPolicy(NoFocus);

    QWidget *top = NULL;
    if (parent)
        top = parent->topLevelWidget();
    if (top){
        raiseWindow(top);
        top->installEventFilter(this);
    }
}
Example #17
0
bool MergeCommand::process(Element* element)
{
    if (element->type() != Element::Range || element->isRow() || element->isColumn()) {
        // TODO Stefan: remove these elements?!
        return true;
    }

    // sanity check
    if (m_sheet->isProtected() || m_sheet->map()->isProtected()) {
        return false;
    }

    QRect range = element->rect();
    int left   = range.left();
    int right  = range.right();
    int top    = range.top();
    int bottom = range.bottom();
    int height = range.height();
    int width  = range.width();

    bool doMerge = m_reverse ? (!m_merge) : m_merge;

    if (doMerge) {
        if (m_mergeHorizontal) {
            for (int row = top; row <= bottom; ++row) {
                int rows = 0;
                for (int col = left; col <= right; ++col) {
                    Cell cell = Cell(m_sheet, col, row);
                    if (cell.doesMergeCells()) {
                        rows = qMax(rows, cell.mergedYCells());
                        cell.mergeCells(col, row, 0, 0);
                    }
                }
                Cell cell = Cell(m_sheet,  left, row);
                if (!cell.isPartOfMerged()) {
                    cell.mergeCells(left, row, width - 1, rows);
                }
            }
        } else if (m_mergeVertical) {
            for (int col = left; col <= right; ++col) {
                int cols = 0;
                for (int row = top; row <= bottom; ++row) {
                    Cell cell = Cell(m_sheet, col, row);
                    if (cell.doesMergeCells()) {
                        cols = qMax(cols, cell.mergedXCells());
                        cell.mergeCells(col, row, 0, 0);
                    }
                }
                Cell cell = Cell(m_sheet, col, top);
                if (!cell.isPartOfMerged()) {
                    cell.mergeCells(col, top, cols, height - 1);
                }
            }
        } else {
            Cell cell = Cell(m_sheet,  left, top);
            cell.mergeCells(left, top, width - 1, height - 1);
        }
    } else { // dissociate
        for (int col = left; col <= right; ++col) {
            for (int row = top; row <= bottom; ++row) {
                Cell cell = Cell(m_sheet, col, row);
                if (!cell.doesMergeCells()) {
                    continue;
                }
                cell.mergeCells(col, row, 0, 0);
            }
        }
    }

    // adjust selection
    if (m_selection)
        m_selection->isEmpty() ? m_selection->initialize(range, m_sheet) : m_selection->extend(range, m_sheet);

    return true;
}
Example #18
0
GeoDataLatLonAltBox EquirectProjection::latLonAltBox( const QRect& screenRect,
                                                      const ViewportParams *viewport ) const
{
    qreal west;
    qreal north = 90*DEG2RAD;
    geoCoordinates( screenRect.left(), screenRect.top(), viewport, west, north, GeoDataCoordinates::Radian );

    qreal east;
    qreal south = -90*DEG2RAD;
    geoCoordinates( screenRect.right(), screenRect.bottom(), viewport, east, south, GeoDataCoordinates::Radian );

    // For the case where the whole viewport gets covered there is a
    // pretty dirty and generic detection algorithm:
    GeoDataLatLonAltBox latLonAltBox;
    latLonAltBox.setNorth( north, GeoDataCoordinates::Radian );
    latLonAltBox.setSouth( south, GeoDataCoordinates::Radian );
    latLonAltBox.setWest( west, GeoDataCoordinates::Radian );
    latLonAltBox.setEast( east, GeoDataCoordinates::Radian );
    latLonAltBox.setMinAltitude(      -100000000.0 );
    latLonAltBox.setMaxAltitude( 100000000000000.0 );

    // Convenience variables
    int  radius = viewport->radius();
    int  width  = viewport->width();

    // The remaining algorithm should be pretty generic for all kinds of 
    // flat projections:

    if ( repeatX() ) {
        int xRepeatDistance = 4 * radius;
        if ( width >= xRepeatDistance ) {
            latLonAltBox.setWest( -M_PI );
            latLonAltBox.setEast( +M_PI );
        }
    }
    else {
        // We need a point on the screen at maxLat that definitely gets displayed:
        qreal averageLatitude = ( latLonAltBox.north() + latLonAltBox.south() ) / 2.0;
    
        GeoDataCoordinates maxLonPoint( +M_PI, averageLatitude, GeoDataCoordinates::Radian );
        GeoDataCoordinates minLonPoint( -M_PI, averageLatitude, GeoDataCoordinates::Radian );
    
        qreal dummyX, dummyY; // not needed
        bool dummyVal;
    
        if ( screenCoordinates( maxLonPoint, viewport, dummyX, dummyY, dummyVal ) ) {
            latLonAltBox.setEast( +M_PI );
        }
        if ( screenCoordinates( minLonPoint, viewport, dummyX, dummyY, dummyVal ) ) {
            latLonAltBox.setWest( -M_PI );
        }
    }

    // Now we need to check whether maxLat (e.g. the north pole) gets displayed
    // inside the viewport.

    // We need a point on the screen at maxLat that definitely gets displayed:
    qreal averageLongitude = latLonAltBox.east();

    GeoDataCoordinates maxLatPoint( averageLongitude, maxLat(), 0.0, GeoDataCoordinates::Radian );
    GeoDataCoordinates minLatPoint( averageLongitude, minLat(), 0.0, GeoDataCoordinates::Radian );

    qreal dummyX, dummyY; // not needed
    bool dummyVal;

    if ( screenCoordinates( maxLatPoint, viewport, dummyX, dummyY, dummyVal ) ) {
        latLonAltBox.setEast( +M_PI );
        latLonAltBox.setWest( -M_PI );
    }
    if ( screenCoordinates( minLatPoint, viewport, dummyX, dummyY, dummyVal ) ) {
        latLonAltBox.setEast( +M_PI );
        latLonAltBox.setWest( -M_PI );
    }

    return latLonAltBox;
}
Example #19
0
/*!
  \brief Draw the symbol into a bounding rectangle.

  This function assumes that the painter has been initialized with
  brush and pen before. This allows a much more performant implementation
  when painting many symbols with the same brush and pen like in curves.

  \param painter Painter
  \param r Bounding rectangle
*/
void QwtSymbol::draw(QPainter *painter, const QRect& r) const
{
    switch(d_style)
    {
        case QwtSymbol::Ellipse:
            QwtPainter::drawEllipse(painter, r);
            break;
        case QwtSymbol::Rect:
            QwtPainter::drawRect(painter, r);
            break;
        case QwtSymbol::Diamond:
        {
            const int w2 = r.width() / 2;
            const int h2 = r.height() / 2;

            QwtPointArray pa(4);
            pa.setPoint(0, r.x() + w2, r.y());
            pa.setPoint(1, r.right(), r.y() + h2);
            pa.setPoint(2, r.x() + w2, r.bottom());
            pa.setPoint(3, r.x(), r.y() + h2);
            QwtPainter::drawPolygon(painter, pa);
            break;
        }
        case QwtSymbol::Cross:
        {
            const int w2 = r.width() / 2;
            const int h2 = r.height() / 2;

            QwtPainter::drawLine(painter, r.x() + w2, r.y(), 
                r.x() + w2, r.bottom());
            QwtPainter::drawLine(painter, r.x(), r.y() + h2, 
                r.right(), r.y() + h2);
            break;
        }
        case QwtSymbol::XCross:
        {
            QwtPainter::drawLine(painter, r.left(), r.top(), 
                r.right(), r.bottom());
            QwtPainter::drawLine(painter, r.left(), r.bottom(), 
                r.right(), r.top());
            break;
        }
        case QwtSymbol::Triangle:
        case QwtSymbol::UTriangle:
        {
            const int w2 = r.width() / 2;

            QwtPointArray pa(3);
            pa.setPoint(0, r.x() + w2, r.y());
            pa.setPoint(1, r.right(), r.bottom());
            pa.setPoint(2, r.x(), r.bottom());
            QwtPainter::drawPolygon(painter, pa);
            break;
        }
        case QwtSymbol::DTriangle:
        {
            const int w2 = r.width() / 2;

            QwtPointArray pa(3);
            pa.setPoint(0, r.x(), r.y());
            pa.setPoint(1, r.right(), r.y());
            pa.setPoint(2, r.x() + w2, r.bottom());
            QwtPainter::drawPolygon(painter, pa);
            break;
        }
        case QwtSymbol::RTriangle:
        {
            const int h2 = r.height() / 2;

            QwtPointArray pa(3);
            pa.setPoint(0, r.x(), r.y());
            pa.setPoint(1, r.right(), r.y() + h2);
            pa.setPoint(2, r.x(), r.bottom());
            QwtPainter::drawPolygon(painter, pa);
            break;
        }
        case QwtSymbol::LTriangle:
        {
            const int h2 = r.height() / 2;

            QwtPointArray pa(3);
            pa.setPoint(0, r.right(), r.y());
            pa.setPoint(1, r.x(), r.y() + h2);
            pa.setPoint(2, r.right(), r.bottom());
            QwtPainter::drawPolygon(painter, pa);
            break;
        }
        default:;
    }
}
void SXBSchView::print(QPrinter*  pPrinter)
{
    m_pDoc->resetSelect();
    updateViewBuffer(true);
    QPainter paint;
    if(paint.begin(pPrinter ) ) {
        int dpi;
#ifdef Q_WS_MACX
        int dpix,dpiy;;
        dpix = pPrinter->logicalDpiX();
        dpiy = pPrinter->logicalDpiY();
        dpi=((dpix < dpiy) ? dpix : dpiy);
#else
        dpi = pPrinter->resolution();
#endif

        paint.setRenderHint(QPainter::Antialiasing, true);


        //    	QRect rcPaper = pPrinter->paperRect();
        //    printf("paperRect %d,%d,%d,%d\n",rcPaper.left(),rcPaper.top(),rcPaper.width(),rcPaper.height());
        QRect rcVp = paint.viewport();
        QRect rcPg = pPrinter->pageRect();
        //    printf("pageRect %d,%d,%d,%d\n",rcPg.left(),rcPg.top(),rcPg.width(),rcPg.height());
        //    	int orientation = pPrinter->orientation();
        //    printf("orientation %d\n",orientation);

        int vpWidth, vpHeight;
        int pgLeft, pgTop, pgWidth, pgHeight;

        vpWidth    =rcVp.width();
        vpHeight = rcVp.height();

        pgLeft    =rcPg.left();
        pgTop    =rcPg.top();
        pgWidth    =rcPg.width();
        pgHeight = rcPg.height();


        //印刷時に印刷の向きを変えてもpageRect()の返す値が変わらないQtのバグ(?)の対策
        if(    	(vpWidth > vpHeight && pgWidth < pgHeight)
                ||    (vpWidth < vpHeight && pgWidth > pgHeight)    ) {
            int swapn;
            swapn = pgLeft;
            pgLeft = pgTop;
            pgTop = swapn;

            swapn = pgWidth;
            pgWidth = pgHeight;
            pgHeight = swapn;
        }

        QSettings *settings = g_cfg.getSettings();

        int leftMargin = 15;
        int topMargin = 15;
        int rightMargin = 15;
        int bottomMargin = 15;

        settings->beginGroup("PrintOption");
        bool color = settings->value("Color",true).toBool();
        settings->endGroup();


        settings->beginGroup("PrintMargin");
        topMargin = settings->value("Top",15).toInt();
        bottomMargin = settings->value("Bottom",15).toInt();
        leftMargin = settings->value("Left",15).toInt();
        rightMargin = settings->value("Right",15).toInt();
        settings->endGroup();

        if      (topMargin    < 0)   topMargin = 0;
        else if (topMargin    > 50)  topMargin = 50;
        if      (bottomMargin < 0)   bottomMargin = 0;
        else if (bottomMargin > 50)  bottomMargin = 50;
        if      (leftMargin   < 0)   leftMargin = 0;
        else if (leftMargin   > 50)  leftMargin = 50;
        if      (rightMargin  < 0)   rightMargin = 0;
        else if (rightMargin  > 50)  rightMargin = 50;

        topMargin = dpi * 10 * topMargin / 254;
        bottomMargin = dpi * 10 * bottomMargin / 254;
        leftMargin = dpi * 10 * leftMargin / 254;
        rightMargin = dpi * 10 * rightMargin / 254;




        //    printf("SXBSchView::print() dpi:%d\n",dpi);

        paint.save();

        paint.setViewTransformEnabled (true);
        paint.resetMatrix();

        SSize size = m_pDoc->SheetSize();
        int w = size.w();
        int h = size.h();

        int dw = w*10;
        int dh = h*10;
        //    p->setWindow( 0,0, dw, dh );
        //    QRect rc = paint.viewport();

        int rightWidth = vpWidth-(pgLeft+pgWidth);
        if(rightWidth < 0) rightWidth = 0;
        int bottomWidth = vpHeight-(pgTop+pgHeight);
        if(bottomWidth < 0) bottomWidth = 0;

        leftMargin -= pgLeft;
        if(leftMargin < 0)leftMargin = 0;

        topMargin -= pgTop;
        if(topMargin < 0) topMargin = 0;

        rightMargin -= rightWidth;
        if(rightMargin < 0) rightMargin = 0;

        bottomMargin -= bottomWidth;
        if(bottomMargin < 0) bottomMargin = 0;

        int vw = pgWidth-(leftMargin+rightMargin);
        int vh = pgHeight-(topMargin+bottomMargin);


        double sheetRatio=(double)w / (double)h;
        double viewRatio=(double)vw / (double)vh;

        int newW;
        int newH;

        if(sheetRatio > viewRatio) {
            newW = vw;
            newH = (int)(vw / sheetRatio);
        } else {
            newH = vh;
            newW = (int)(vh *  sheetRatio);
        }
        //    printf("newW,H=%d,%d\n",newW,newH);
        //     p->setViewport(     rc.left() + (vw-newW)/2,
        //    	    	    rc.top() + (vh-newH)/2,
        //    	    	    newW, newH );
        //    QRect rcvp = p->viewport();
        //    printf("x,y,w,h  %d,%d,%d,%d\n",rcvp.x(),rcvp.y(),rcvp.width(),rcvp.height());

        paint.setViewport( leftMargin+ (vw-newW)/2,
                           topMargin + (vh-newH)/2,
                           newW, newH );
        paint.setWindow( 0,0, dw, dh );


        //    rcvp = p->viewport();
        //    printf("x,y,w,h  %d,%d,%d,%d\n",rcvp.x(),rcvp.y(),rcvp.width(),rcvp.height());


        QRect rcClip = QRect(0,0,dw,dh);
        SRect srcClip =SRect(0,0,w,h);

        paint.setBackground(Qt::white);
        paint.eraseRect(0,0,dw,dh);
        g_drawFrame(&paint,size,rcClip,Qt::black,1,10);
        drawMainXBSchObj(&paint,(color ? DRAW_ON : DRAW_MONO)|DRAW_FOR_PRINT,&srcClip,false,1,10);
        paint.restore();

        paint.end();
    }
}
Example #21
0
/*!
  Recalculate the QwtThermo geometry and layout based on
  the QwtThermo::contentsRect() and the fonts.

  \param update_geometry notify the layout system and call update
         to redraw the scale
*/
void QwtThermo::layoutThermo( bool update_geometry )
{
    const QRect tRect = pipeRect();
    const int bw = d_data->borderWidth + d_data->spacing;
    const bool inverted = ( maxValue() < minValue() );

    int from, to;

    if ( d_data->orientation == Qt::Horizontal )
    {
        from = tRect.left();
        to = tRect.right();

        if ( d_data->rangeFlags & QwtInterval::ExcludeMinimum )
        {
            if ( inverted )
                to++;
            else
                from--;
        }
        if ( d_data->rangeFlags & QwtInterval::ExcludeMaximum )
        {
            if ( inverted )
                from--;
            else
                to++;
        }

        switch ( d_data->scalePos )
        {
            case TopScale:
            {
                scaleDraw()->setAlignment( QwtScaleDraw::TopScale );
                scaleDraw()->move( from, tRect.top() - bw );
                scaleDraw()->setLength( to - from );
                break;
            }

            case BottomScale:
            case NoScale: 
            default:
            {
                scaleDraw()->setAlignment( QwtScaleDraw::BottomScale );
                scaleDraw()->move( from, tRect.bottom() + bw );
                scaleDraw()->setLength( to - from );
                break;
            }
        }

        d_data->map.setPaintInterval( from, to );
    }
    else // Qt::Vertical
    {
        from = tRect.top();
        to = tRect.bottom();

        if ( d_data->rangeFlags & QwtInterval::ExcludeMinimum )
        {
            if ( inverted )
                from--;
            else
                to++;
        }
        if ( d_data->rangeFlags & QwtInterval::ExcludeMaximum )
        {
            if ( inverted )
                to++;
            else
                from--;
        }

        switch ( d_data->scalePos )
        {
            case RightScale:
            {
                scaleDraw()->setAlignment( QwtScaleDraw::RightScale );
                scaleDraw()->move( tRect.right() + bw, from );
                scaleDraw()->setLength( to - from );
                break;
            }

            case LeftScale:
            case NoScale: 
            default:
            {
                scaleDraw()->setAlignment( QwtScaleDraw::LeftScale );
                scaleDraw()->move( tRect.left() - bw, from );
                scaleDraw()->setLength( to - from );
                break;
            }
        }
        d_data->map.setPaintInterval( to, from );
    }

    if ( update_geometry )
    {
        updateGeometry();
        update();
    }
}
//再描画
void SXBSchView::drawContents(QPainter*p,int clipx,int clipy,int clipw,int cliph)
{
    //    qDebug("SXBSchView::drawContents\n");

    updateViewBuffer();// clipx, clipy, clipw, cliph );

    QRect rcClip = QRect(clipx,clipy,clipw,cliph);
    QRect rcClipSheet = ContentsToSheet(rcClip);
    SRect srcClipSheet =SRect(rcClipSheet.left(),rcClipSheet.top(),rcClipSheet.width(),rcClipSheet.height());


    //int vclipx,vclipy;
    //    p->setClipping(true);
    //contentsToViewport ( clipx,clipy,vclipx,vclipy);
    //    p->setClipRect(vclipx,vclipy,clipw,cliph);

    p->drawPixmap(0,0,m_viewBuffer);
    //    p->drawPixmap(clipx,clipy,m_viewBuffer,vclipx,vclipy,clipw,cliph);
    //Qt4    	bitBlt(viewport(),clipx,clipy,&m_viewBuffer,clipx,clipy,clipw,cliph);//,Qt::CopyROP,false);




    //////////////////////////////////////////////////////////////
    /*
        p->eraseRect(clipx,clipy,clipw,cliph);

        SSize size = m_pDoc->SheetSize();
        g_drawFrame(p,size,rcClip,QColor("black"),m_viewScale,m_viewScaleMul);
        if(m_bDisplayGrid){
                drawGrid(p,rcClipSheet,QColor("green4"));
        }
        drawMainXBSchObj(p,DRAW_ON,&srcClipSheet, m_viewScale,m_viewScaleMul);

        if((m_moveOption == MOVE_OPTION_COMPONENT_NAME)  || (m_moveOption == MOVE_OPTION_COMPONENT_NUM)){
                int modeOption = 0;
                if(m_moveOption == MOVE_OPTION_COMPONENT_NAME){
                        modeOption = DRAW_INH_PARTNAME;
                }else{
                        modeOption = DRAW_INH_PARTNUM;
                }
                drawTempXBSchObj(p,DRAW_TEMP|modeOption,&srcClipSheet);
        }


    */
    //////////////////////////////////////////////////////////////
    //他のすべての描画が終わってからTempデータの描画を行う
    int modeOption = 0;
    if(m_pDoc->m_listTemp.size()>0) {
        if(m_bCompleteDrawTemp) {
            if(m_moveOption == MOVE_OPTION_COMPONENT_NAME) {
                modeOption = (DRAW_INH_PARTNUM | DRAW_INH_PARTBODY);
            } else if(m_moveOption == MOVE_OPTION_COMPONENT_NUM) {
                modeOption = (DRAW_INH_PARTNAME | DRAW_INH_PARTBODY);
            }

            drawTempXBSchObj(p,DRAW_TEMP|modeOption,&srcClipSheet);
        }
        if(m_clearTempRect) {
            m_pDoc->setupRcTempArea();
            m_pDoc->setupRotateRect();
            m_clearTempRect = false;
        }
        if(!modeOption) {
            drawTempDataFrame(p);
        }
    }


    if(m_bDrawSelectFrame) drawSelectFrame(p);
    if(m_bDrawTempLine)    drawTempLine(p);
    if(m_pCursorObj) drawCursorObj(p);
}
Example #23
0
QRegion QDecorationStyled::region(const QWidget *widget, const QRect &rect, int decorationRegion)
{
    QStyle *style = QApplication::style();

    // In the case of a borderless title bar, the title bar must be expanded one
    // borderWidth to the left, right and up.
    bool noTitleBorder = style->styleHint(QStyle::SH_TitleBar_NoBorder, 0, widget);
    int borderWidth = style->pixelMetric(QStyle::PM_MDIFrameWidth, 0, 0);
    int titleHeight = titleBarHeight(widget) + (noTitleBorder ? borderWidth : 0);
    int titleExtra = noTitleBorder ? borderWidth : 0;

    QRect inside = QRect(rect.x() - titleExtra, rect.top() - titleHeight,
                         rect.width() + 2 * titleExtra, titleHeight);

    Qt::WindowFlags flags = widget->windowFlags();
    bool hasSysMenu = flags & Qt::WindowSystemMenuHint;
    bool hasContextHelp = flags & Qt::WindowContextHelpButtonHint;
    bool hasMinimize = flags & Qt::WindowMinimizeButtonHint;
    bool hasMaximize = flags & Qt::WindowMaximizeButtonHint;

    QStyleOptionTitleBar opt;
    opt.subControls = QStyle::SC_TitleBarLabel
                      | QStyle::SC_TitleBarSysMenu
                      | QStyle::SC_TitleBarNormalButton
                      | QStyle::SC_TitleBarMinButton
                      | QStyle::SC_TitleBarMaxButton
                      | QStyle::SC_TitleBarCloseButton;
    opt.titleBarFlags = widget->windowFlags();
    opt.direction = QApplication::layoutDirection();
    opt.text = windowTitleFor(widget);
    opt.icon = widget->windowIcon();
    opt.rect = inside;

    QRegion region;
    switch (decorationRegion) {
    case Title:
        region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                       QStyle::SC_TitleBarLabel, 0);
        break;
    case Menu:
        if (hasSysMenu)
            region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                           QStyle::SC_TitleBarSysMenu, 0);
        break;
    case Help:
        if (hasContextHelp)
            region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                           QStyle::SC_TitleBarContextHelpButton,
                                           0);
        break;
    case Normalize:
        if (hasMaximize | hasMinimize)
            region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                           QStyle::SC_TitleBarNormalButton,
                                           0);
        break;
    case Minimize:
        if (hasMinimize)
            region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                           QStyle::SC_TitleBarMinButton,
                                           0);
        break;
    case Maximize:
        if (hasMaximize)
            region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                           QStyle::SC_TitleBarMaxButton,
                                           0);
        break;
    case Close:
        region = style->subControlRect(QStyle::CC_TitleBar, &opt,
                                       QStyle::SC_TitleBarCloseButton, 0);
        break;

    default:
        region = QDecorationDefault::region(widget, rect, decorationRegion);
    }

    opt.rect = QRect(rect.x() - titleExtra, rect.top() - titleHeight,
                         rect.width() + 2 * titleExtra,
                         rect.height() + titleHeight + titleExtra);

    QStyleHintReturnMask mask;
    style->styleHint(QStyle::SH_WindowFrame_Mask, &opt, 0, &mask);

    return (mask.region.isEmpty() ? region : (region & mask.region));
}
Example #24
0
void DDateEdit::showPopup()
{
    if ( d->readOnly )
    {
        return;
    }

    QRect desk          = KGlobalSettings::desktopGeometry( this );
    QPoint popupPoint   = mapToGlobal( QPoint( 0,0 ) );
    int dateFrameHeight = d->popup->sizeHint().height();

    if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() )
    {
        popupPoint.setY( popupPoint.y() - dateFrameHeight );
    }
    else
    {
        popupPoint.setY( popupPoint.y() + height() );
    }

    int dateFrameWidth = d->popup->sizeHint().width();

    if ( popupPoint.x() + dateFrameWidth > desk.right() )
    {
        popupPoint.setX( desk.right() - dateFrameWidth );
    }

    if ( popupPoint.x() < desk.left() )
    {
        popupPoint.setX( desk.left() );
    }

    if ( popupPoint.y() < desk.top() )
    {
        popupPoint.setY( desk.top() );
    }

    if ( d->date.isValid() )
    {
        d->popup->setDate( d->date );
    }
    else
    {
        d->popup->setDate( QDate::currentDate() );
    }

    d->popup->popup( popupPoint );

    // The combo box is now shown pressed. Make it show not pressed again
    // by causing its (invisible) list box to emit a 'selected' signal.
    // First, ensure that the list box contains the date currently displayed.
    QDate date = parseDate();
    assignDate( date );
    updateView();
    // Now, simulate an Enter to unpress it
    QAbstractItemView* lb = view();

    if (lb)
    {
        lb->setCurrentIndex( lb->model()->index( 0, 0 ) );
        QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
        QApplication::postEvent(lb, keyEvent);
    }
}
Example #25
0
void MythUIEditBar::Display(void)
{
    QRect keeparea = QRect();
    QRect cutarea  = QRect();
    MythUIType *position    = GetChild("position");
    MythUIType *keep        = GetChild("keep");
    MythUIType *cut         = GetChild("cut");
    MythUIType *cuttoleft   = GetChild("cuttoleft");
    MythUIType *cuttoright  = GetChild("cuttoright");
    MythUIType *keeptoleft  = GetChild("keeptoleft");
    MythUIType *keeptoright = GetChild("keeptoright");

    if (position)
        position->SetVisible(false);

    if (keep)
    {
        keep->SetVisible(false);
        keeparea = keep->GetArea();
    }

    if (cut)
    {
        cut->SetVisible(false);
        cutarea = cut->GetArea();
    }
    if (cuttoleft)
        cuttoleft->SetVisible(false);
    if (cuttoright)
        cuttoright->SetVisible(false);
    if (keeptoleft)
        keeptoleft->SetVisible(false);
    if (keeptoright)
        keeptoright->SetVisible(false);

    if (position && keeparea.isValid())
    {
        int offset = position->GetArea().width() / 2;
        int newx   = (int)(((float)keeparea.width() * m_position) + 0.5f);
        int newy   = position->GetArea().top();
        position->SetPosition(newx - offset, newy);
        position->SetVisible(true);
    }

    ClearImages();
    if (!m_regions.size())
    {
        if (keep)
            keep->SetVisible(true);
        return;
    }

    MythUIShape *barshape   = dynamic_cast<MythUIShape*>(cut);
    MythUIImage *barimage   = dynamic_cast<MythUIImage*>(cut);
    MythUIShape *leftshape  = dynamic_cast<MythUIShape*>(cuttoleft);
    MythUIImage *leftimage  = dynamic_cast<MythUIImage*>(cuttoleft);
    MythUIShape *rightshape = dynamic_cast<MythUIShape*>(cuttoright);
    MythUIImage *rightimage = dynamic_cast<MythUIImage*>(cuttoright);

    QListIterator<QPair<float,float> > regions(m_regions);
    while (regions.hasNext() && cutarea.isValid())
    {
        QPair<float,float> region = regions.next();
        int left  = (int)((region.first * cutarea.width()) + 0.5f);
        int right = (int)((region.second * cutarea.width()) + 0.5f);
        if (left >= right)
            right = left + 1;
        if (cut)
        {
            AddBar(barshape, barimage, QRect(left, cutarea.top(), right - left,
                                             cutarea.height()));
        }

        if (cuttoleft && (region.second < 1.0f))
            AddMark(leftshape, leftimage, right, true);

        if (cuttoright && (region.first > 0.0f))
            AddMark(rightshape, rightimage, left, false);
    }

    CalcInverseRegions();

    barshape   = dynamic_cast<MythUIShape*>(keep);
    barimage   = dynamic_cast<MythUIImage*>(keep);
    leftshape  = dynamic_cast<MythUIShape*>(keeptoleft);
    leftimage  = dynamic_cast<MythUIImage*>(keeptoleft);
    rightshape = dynamic_cast<MythUIShape*>(keeptoright);
    rightimage = dynamic_cast<MythUIImage*>(keeptoright);

    QListIterator<QPair<float,float> > regions2(m_invregions);
    while (regions2.hasNext() && keeparea.isValid())
    {
        QPair<float,float> region = regions2.next();
        int left  = (int)((region.first * keeparea.width()) + 0.5f);
        int right = (int)((region.second * keeparea.width()) + 0.5f);
        if (left >= right)
            right = left + 1;
        if (keep)
        {
            AddBar(barshape, barimage, QRect(left, keeparea.top(), right - left,
                                             keeparea.height()));
        }

        if (keeptoleft && (region.second < 1.0f))
            AddMark(leftshape, leftimage, right, true);

        if (keeptoright && (region.first > 0.0f))
            AddMark(rightshape, rightimage, left, false);
    }

    if (position)
        position->MoveToTop();
}
Example #26
0
void TabBarWidget::showPreview(int index)
{
	if (index >= 0 && m_clickedTab < 0)
	{
		if (!m_previewWidget)
		{
			m_previewWidget = new PreviewWidget(this);
		}

		QPoint position;
		QRect rectangle = tabRect(index);
		rectangle.moveTo(mapToGlobal(rectangle.topLeft()));

		m_previewWidget->setPreview(getTabProperty(index, QLatin1String("title"), tr("(Untitled)")).toString(), ((index == currentIndex()) ? QPixmap() : getTabProperty(index, "thumbnail", QPixmap()).value<QPixmap>()));

		switch (shape())
		{
			case QTabBar::RoundedEast:
				position = QPoint((rectangle.left() - m_previewWidget->width()), qMax(0, ((rectangle.bottom() - (rectangle.height() / 2)) - (m_previewWidget->height() / 2))));

				break;
			case QTabBar::RoundedWest:
				position = QPoint(rectangle.right(), qMax(0, ((rectangle.bottom() - (rectangle.height() / 2)) - (m_previewWidget->height() / 2))));

				break;
			case QTabBar::RoundedSouth:
				position = QPoint(qMax(0, ((rectangle.right() - (rectangle.width() / 2)) - (m_previewWidget->width() / 2))), (rectangle.top() - m_previewWidget->height()));

				break;
			default:
				position = QPoint(qMax(0, ((rectangle.right() - (rectangle.width() / 2)) - (m_previewWidget->width() / 2))), rectangle.bottom());

				break;
		}

		const QRect screen = QApplication::desktop()->screenGeometry(this);

		if ((position.x() + m_previewWidget->width()) > screen.bottomRight().x())
		{
			position.setX(screen.width() - m_previewWidget->width());
		}

		if ((position.y() + m_previewWidget->height()) > screen.bottomRight().y())
		{
			position.setY(screen.height() - m_previewWidget->height());
		}

		if (m_previewWidget->isVisible())
		{
			m_previewWidget->setPosition(position);
		}
		else
		{
			m_previewWidget->move(position);
			m_previewWidget->show();
		}
	}
	else if (m_previewWidget)
	{
		m_previewWidget->hide();
	}
}
Example #27
0
bool PunchFilter::Punch(const QImage &img, QImage *outputImage, const QRect &clipRect /*= QRect()*/ ) const
{
    *outputImage = img;
    int top = 0;
    int bottom = img.height();
    int left = 0;
    int right = img.width();

    if (!clipRect.isNull()) {
        // If we have a cliprect, set our coordinates to our cliprect
        // and make sure it is within the boundaries of the image
        // After that, an optimization where we adjust the cliprect to only be the bounding 
        // rect of the circle we are manipulating, (so that we don't have to run the filter on 
        // the whole image if the default cliprect was given).
        top = qMax(top, clipRect.top());
        top = qMax(top, (int)(ceil(m_Center.y() - 1) - m_Radius));
        bottom = qMin(bottom, clipRect.bottom());
        bottom = qMin(bottom, (int)(floor(m_Center.y() + 1) + m_Radius));
        left = qMax(left, clipRect.left());
        left = qMax(left, (int)(ceil(m_Center.x() - 1) - m_Radius));
        right = qMin(right, clipRect.right());
        right = qMin(right, (int)(floor(m_Center.x() + 1) + m_Radius));
    }

    qreal centerx = m_Center.x();
    qreal centery = m_Center.y();

    int x;
    int y;
    double amplitude = m_Force/3.2; // scale down
    //amplitude = qBound(-0.3125, amplitude, 0.3125);

    for (y = top; y < bottom; y++) {
        for (x = left; x < right; x++) {
            qreal dx = x - centerx;
            qreal dy = y - centery;
            double distance = sqrt(dx * dx + dy * dy);
            QRgb rgb;
            if (distance <= m_Radius + M_SQRT2) {   // M_SQRT2 is the maximum "width" of a pixel. (If measured diagonally)
                                                    // we must evaluate this area "outside" the radius also to reduce aliasing effects.
                double distort = distance / m_Radius;
                if (distort > 0.0 && distort < 1.0) {
                    distort = punch_xform(distort, amplitude);
                }
                
                // Normalize the distance vector and find the length after distortion
                if (dx != 0 || dy != 0) {
                    double mag = m_Radius/sqrt(dx * dx + dy * dy);
                    mag *= distort;
                    dx *= mag;
                    dy *= mag;
                }

                double tx = centerx + dx;
                double ty = centery + dy;
                // Crop off any overflows. This happens since we are adding M_SQRT2 to the radius to evaluate a small area outside the radius circle.
                if (tx > img.width()  || tx < 0) tx = x;
                if (ty > img.height() || ty < 0) ty = y;
                
                rgb = getSubpixel(img, tx, ty);
                outputImage->setPixel(x, y, rgb);
            }
        }
    }
    return true;
}
Example #28
0
void QgsMapOverviewCanvas::mouseReleaseEvent( QMouseEvent * e )
{
//  if (mPanningWidget->isHidden())
//    return;

  if ( e->button() == Qt::LeftButton )
  {
    // set new extent
    const QgsMapToPixel& cXf = mSettings.mapToPixel();
    QRect rect = mPanningWidget->geometry();

    QgsPoint center = cXf.toMapCoordinates( rect.center() );
    QgsRectangle oldExtent = mMapCanvas->extent();
    QgsRectangle ext;
    ext.setXMinimum( center.x() - oldExtent.width() / 2 );
    ext.setXMaximum( center.x() + oldExtent.width() / 2 );
    ext.setYMinimum( center.y() - oldExtent.height() / 2 );
    ext.setYMaximum( center.y() + oldExtent.height() / 2 );

    QgsDebugMsg( QString( "panning: new position: [%1,%2] [%3x%4]" ).arg( rect.left() ).arg( rect.top() ).arg( rect.width() ).arg( rect.height() ) );

    mMapCanvas->setExtent( ext );
    mMapCanvas->refresh();
  }
}
void UIGChooserItemMachine::paintBackground(QPainter *pPainter, const QRect &rect)
{
    /* Save painter: */
    pPainter->save();

    /* Prepare color: */
    QPalette pal = palette();

    /* Selection background: */
    if (model()->selectionList().contains(this))
    {
        /* Highlight color: */
        QColor highlight = pal.color(QPalette::Highlight);

        /* Calculate top rectangle: */
        QRect tRect = rect;
        tRect.setBottom(tRect.top() + tRect.height() / 3);
        /* Calculate bottom rectangle: */
        QRect bRect = rect;
        bRect.setTop(bRect.bottom() - bRect.height() / 3);
        /* Calculate middle rectangle: */
        QRect midRect = QRect(tRect.bottomLeft(), bRect.topRight());

        /* Prepare top gradient: */
        QLinearGradient tGradient(tRect.bottomLeft(), tRect.topLeft());
        tGradient.setColorAt(1, highlight.darker(blackoutDarkness()));
        tGradient.setColorAt(0, highlight.darker(defaultDarkness()));
        /* Prepare bottom gradient: */
        QLinearGradient bGradient(bRect.topLeft(), bRect.bottomLeft());
        bGradient.setColorAt(0, highlight.darker(defaultDarkness()));
        bGradient.setColorAt(1, highlight.darker(blackoutDarkness()));

        /* Paint all the stuff: */
        pPainter->fillRect(midRect, highlight.darker(defaultDarkness()));
        pPainter->fillRect(tRect, tGradient);
        pPainter->fillRect(bRect, bGradient);
    }

    /* Hovering background: */
    if (isHovered())
    {
        /* Choose color: */
        QColor baseLight = model()->selectionList().contains(this) ? pal.color(QPalette::Active, QPalette::Highlight) :
                                                                     QColor(Qt::white);
        QColor blurBase = model()->selectionList().contains(this) ? pal.color(QPalette::Active, QPalette::Highlight) :
                                                                    QColor(Qt::white);
        if (!model()->selectionList().contains(this) && !parentItem()->isRoot())
            blurBase = blurBase.darker(defaultDarkness());
        blurBase.setAlpha(0);

        /* Draw background for blur: */
        QImage background(rect.size(), QImage::Format_ARGB32);
        background.fill(blurBase.rgba());

        /* Add blur itself: */
        QPainter blurPainter(&background);
        blurPainter.setBrush(baseLight.darker(animationDarkness()));
        blurPainter.setPen(Qt::NoPen);
        blurPainter.drawRoundedRect(rect.adjusted(5, 5, -5, -5), 5, 5);
        blurPainter.end();
        QImage bluredBackground(rect.size(), QImage::Format_ARGB32);
        blurImage(background, bluredBackground, 5);

        /* Paint highlight bar: */
        pPainter->drawImage(QPoint(0, 0), bluredBackground);
    }

    /* Paint drag token UP? */
    if (dragTokenPlace() != DragToken_Off)
    {
        /* Window color: */
        QColor base = pal.color(QPalette::Active, model()->selectionList().contains(this) ?
                                QPalette::Highlight : QPalette::Window);
        QLinearGradient dragTokenGradient;
        QRect dragTokenRect = rect;
        if (dragTokenPlace() == DragToken_Up)
        {
            dragTokenRect.setHeight(5);
            dragTokenGradient.setStart(dragTokenRect.bottomLeft());
            dragTokenGradient.setFinalStop(dragTokenRect.topLeft());
        }
        else if (dragTokenPlace() == DragToken_Down)
        {
            dragTokenRect.setTopLeft(dragTokenRect.bottomLeft() - QPoint(0, 5));
            dragTokenGradient.setStart(dragTokenRect.topLeft());
            dragTokenGradient.setFinalStop(dragTokenRect.bottomLeft());
        }
        dragTokenGradient.setColorAt(0, base.darker(blackoutDarkness()));
        dragTokenGradient.setColorAt(1, base.darker(dragTokenDarkness()));
        pPainter->fillRect(dragTokenRect, dragTokenGradient);
    }

    /* Restore painter: */
    pPainter->restore();
}
Example #30
0
void PropTreeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	QStyleOptionViewItem itemOpts = option;
	itemOpts.state &= ~QStyle::State_HasFocus;
	PropTreeItem* item = (PropTreeItem*) m_parent->indexToItem(index);
	if ((index.column() == 1) && (item->m_type == PropTreeItem::CheckBox) && !(option.state & QStyle::State_Editing))
	{
		QStyleOptionButton buttonOption;
		buttonOption.rect = option.rect;
		buttonOption.palette = option.palette;
		if (index.model()->data(index, Qt::UserRole).toBool())
			buttonOption.state |= QStyle::State_On;
		else
			buttonOption.state |= QStyle::State_Off;
		QApplication::style()->drawControl(QStyle::CE_CheckBox, &buttonOption, painter);
	}
	else if (index.column() == 0)
	{
		int i = 9; // ### hardcoded in qcommonstyle.cpp
		QRect r = option.rect;
		if (item && (item->childCount() > 0))
		{
			painter->save();
			if (option.state & QStyle::State_Enabled)
				painter->setBrush(Qt::black);
			else
				painter->setBrush(Qt::gray);
			painter->setPen(Qt::NoPen);
			QRect rect = QRect(r.left()+6, r.top()+6, r.height()-12, r.height()-12);
			QPolygon pa(3);
			if (item->isExpanded())
			{
				pa.setPoint(0, rect.left(), rect.top());
				pa.setPoint(1, rect.right(), rect.top());
				pa.setPoint(2, rect.center().x(), rect.bottom());
			}
			else
			{
				pa.setPoint(0, rect.left(), rect.top());
				pa.setPoint(1, rect.left(), rect.bottom());
				pa.setPoint(2, rect.right(), rect.center().y());
			}
			painter->setRenderHint(QPainter::Antialiasing, true);
			painter->drawPolygon(pa);
			painter->restore();
		}
		painter->save();
		if (item && (item->QTreeWidgetItem::parent()))
			i = 15;
		if (item && (item->treeWidget()->currentItem() == item))
		{
			itemOpts.font.setBold(true);
			painter->setFont(itemOpts.font);
		}
		QRect textrect = QRect(r.left() + i*2, r.top(), r.width() - (i * 2), r.height());
	//	QString text = itemOpts.fontMetrics.elidedText(index.model()->data(index, Qt::DisplayRole).toString(), Qt::ElideMiddle, itemOpts.rect.width(), Qt::TextShowMnemonic);
		QString text = index.model()->data(index, Qt::DisplayRole).toString();
		QApplication::style()->drawItemText(painter, textrect, Qt::AlignVCenter | Qt::AlignLeft | Qt::TextShowMnemonic, itemOpts.palette, (itemOpts.state & QStyle::State_Enabled), text, QPalette::Text);
		painter->restore();
	}
	else
		QItemDelegate::paint(painter, itemOpts, index);
	QColor color = static_cast<QRgb>(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &option));
	painter->save();
	painter->setPen(QPen(color));
	painter->drawLine(option.rect.x(), option.rect.top(), option.rect.x(), option.rect.bottom());
	painter->restore();
}