Example #1
0
void AreaDialog::paintEvent(QPaintEvent* e)
{
  Q_UNUSED(e);

  if (mGrabbing) // grabWindow() should just get the background
    return;

  QPainter painter(this);

  QPalette pal = palette();
  QFont font   = QToolTip::font();

  QColor handleColor(85, 160, 188, 220);
  QColor overlayColor(0, 0, 0, mOverlayAlpha);
  QColor textColor = pal.color(QPalette::Active, QPalette::Text);
  QColor textBackgroundColor = pal.color(QPalette::Active, QPalette::Base);
  painter.drawPixmap(0, 0, mScreenshot->pixmap());
  painter.setFont(font);

  QRect r = mSelection.normalized().adjusted(0, 0, -1, -1);

  QRegion grey(rect());
  grey = grey.subtracted(r);
  painter.setPen(handleColor);
  painter.setBrush(overlayColor);
  painter.setClipRegion(grey);
  painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1);
  painter.setClipRect(rect());
  painter.setBrush(Qt::NoBrush);
  painter.drawRect(r);

  if (mShowHelp) {
    //Drawing the explanatory text.
    QRect helpRect = qApp->desktop()->screenGeometry(qApp->desktop()->primaryScreen());
    QString helpTxt = tr("Lightscreen area mode:\nUse your mouse to draw a rectangle to capture.\nPress any key or right click to exit.");

    helpRect.setHeight(qRound((float)(helpRect.height() / 10))); // We get a decently sized rect where the text should be drawn (centered)

    // We draw the white contrasting background for the text, using the same text and options to get the boundingRect that the text will have.
    painter.setPen(QPen(Qt::white));
    painter.setBrush(QBrush(QColor(255, 255, 255, 180), Qt::SolidPattern));
    QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt);

    // These four calls provide padding for the rect
    bRect.setWidth(bRect.width() + 12);
    bRect.setHeight(bRect.height() + 10);
    bRect.setX(bRect.x() - 12);
    bRect.setY(bRect.y() - 10);

    painter.drawRoundedRect(bRect, 8, 8);

    // Draw the text:
    painter.setPen(QPen(Qt::black));
    painter.drawText(helpRect, Qt::AlignCenter, helpTxt);
  }

  if (!mSelection.isNull()) {
    // The grabbed region is everything which is covered by the drawn
    // rectangles (border included). This means that there is no 0px
    // selection, since a 0px wide rectangle will always be drawn as a line.
    QString txt = QString("%1x%2").arg(mSelection.width() == 0 ? 2 : mSelection.width())
        .arg(mSelection.height() == 0 ? 2 : mSelection.height());
    QRect textRect = painter.boundingRect(rect(), Qt::AlignLeft, txt);
    QRect boundingRect = textRect.adjusted(-4, 0, 0, 0);

    if (textRect.width() < r.width() - 2*mHandleSize &&
       textRect.height() < r.height() - 2*mHandleSize &&
       (r.width() > 100 && r.height() > 100)) // center, unsuitable for small selections
    {
      boundingRect.moveCenter(r.center());
      textRect.moveCenter(r.center());
    }
    else if (r.y() - 3 > textRect.height() &&
      r.x() + textRect.width() < rect().right()) // on top, left aligned
    {
      boundingRect.moveBottomLeft(QPoint(r.x(), r.y() - 3));
      textRect.moveBottomLeft(QPoint(r.x() + 2, r.y() - 3));
    }
    else if (r.x() - 3 > textRect.width()) // left, top aligned
    {
      boundingRect.moveTopRight(QPoint(r.x() - 3, r.y()));
      textRect.moveTopRight(QPoint(r.x() - 5, r.y()));
    }
    else if (r.bottom() + 3 + textRect.height() < rect().bottom() &&
      r.right() > textRect.width()) // at bottom, right aligned
    {
      boundingRect.moveTopRight(QPoint(r.right(), r.bottom() + 3));
      textRect.moveTopRight(QPoint(r.right() - 2, r.bottom() + 3));
    }
    else if (r.right() + textRect.width() + 3 < rect().width()) // right, bottom aligned
    {
      boundingRect.moveBottomLeft(QPoint(r.right() + 3, r.bottom()));
      textRect.moveBottomLeft(QPoint(r.right() + 5, r.bottom()));
    }
    // if the above didn't catch it, you are running on a very tiny screen...
    painter.setPen(textColor);
    painter.setBrush(textBackgroundColor);
    painter.drawRect(boundingRect);
    painter.drawText(textRect, txt);

    if ((r.height() > mHandleSize*2 && r.width() > mHandleSize*2)
      || !mMouseDown)
    {
      updateHandles();
      painter.setPen(handleColor);
      handleColor.setAlpha(80);
      painter.setBrush(handleColor);
      painter.drawRects(handleMask().rects());
    }
  }

  if (!mScreenshot->options().magnify)
    return;

  // Drawing the magnified version
  QPoint magStart, magEnd, drawPosition;
  QRect newRect;

  QRect pixmapRect = mScreenshot->pixmap().rect();

  if (mMouseMagnifier) {
    drawPosition = mMousePos - QPoint(100, 100);

    magStart = mMousePos - QPoint(50, 50);
    magEnd = mMousePos + QPoint(50, 50);

    newRect = QRect(magStart, magEnd);
  }
  else {
    // So pretty.. oh so pretty.
    if (mMouseOverHandle == &mTLHandle)
      magStart = mSelection.topLeft();
    else if (mMouseOverHandle == &mTRHandle)
      magStart = mSelection.topRight();
    else if (mMouseOverHandle == &mBLHandle)
      magStart = mSelection.bottomLeft();
    else if (mMouseOverHandle == &mBRHandle)
      magStart = mSelection.bottomRight();
    else if (mMouseOverHandle == &mLHandle)
      magStart = QPoint(mSelection.left(), mSelection.center().y());
    else if (mMouseOverHandle == &mTHandle)
      magStart = QPoint(mSelection.center().x(), mSelection.top());
    else if (mMouseOverHandle == &mRHandle)
      magStart = QPoint(mSelection.right(), mSelection.center().y());
    else if (mMouseOverHandle == &mBHandle)
      magStart =  QPoint(mSelection.center().x(), mSelection.bottom());
    else if (mMouseOverHandle == 0)
      magStart = mMousePos;

    magEnd = magStart;
    drawPosition = mSelection.bottomRight();

    magStart -= QPoint(50, 50);
    magEnd   += QPoint(50, 50);

    newRect = QRect(magStart, magEnd);

    if ((drawPosition.x()+newRect.width()*2) > pixmapRect.width())
      drawPosition.setX(drawPosition.x()-newRect.width()*2);

    if ((drawPosition.y()+newRect.height()*2) > pixmapRect.height())
      drawPosition.setY(drawPosition.y()-newRect.height()*2);

    if (drawPosition.y() == mSelection.bottomRight().y()-newRect.height()*2
     && drawPosition.x() == mSelection.bottomRight().x()-newRect.width()*2)
      painter.setOpacity(0.7);
  }

  if (!pixmapRect.contains(newRect, true) || drawPosition.x() <= 0 || drawPosition.y() <= 0)  {
    return;
  }

  QPixmap magnified = mScreenshot->pixmap().copy(newRect).scaled(QSize(newRect.width()*2, newRect.height()*2));

  QPainter magPainter(&magnified);
  magPainter.setPen(QPen(QBrush(QColor(35, 35, 35)), 2)); // Same border pen
  magPainter.drawRect(magnified.rect());

  if (!mMouseMagnifier) {
    magPainter.drawText(magnified.rect().center()-QPoint(4, -4), "+"); //Center minus the 4 pixels wide and across of the "+" -- TODO: Test alternative DPI settings.
  }

  painter.drawPixmap(drawPosition, magnified);
}
Example #2
0
QPoint GLDMaskBox::calcPosOfOwner()
{
    QPoint pt(0, 0);

    do
    {
        // 计算owner位置对应屏幕中心的象限
        if (!m_oTipBoxParam.m_wgtOwner)
        {
            break;
        }

        QPoint ptGlobalOwnerCenter = m_oTipBoxParam.m_wgtOwner->mapToGlobal(
            m_oTipBoxParam.m_wgtOwner->rect().center());
        QPoint ptGlobalScreen = QApplication::desktop()->screenGeometry().center();
        QPoint ptDelta = ptGlobalOwnerCenter - ptGlobalScreen;

        if (ptDelta.x() >= 0 && ptDelta.y() <= 0)
        {
            // 第一象限
            pt = QPoint(ptGlobalOwnerCenter.x() - m_oTipBoxParam.m_wgtOwner->width()/2,
                            ptGlobalOwnerCenter.y() + m_oTipBoxParam.m_wgtOwner->height()/2);
            pt += QPoint(-this->width()/2, 0);
        }
        else if (ptDelta.x() <= 0 && ptDelta.y() <= 0)
        {
            // 第二象限
            pt = QPoint(ptGlobalOwnerCenter.x() + m_oTipBoxParam.m_wgtOwner->width()/2,
                            ptGlobalOwnerCenter.y() + m_oTipBoxParam.m_wgtOwner->height()/2);
            pt += QPoint(-this->width()/2, 0);
        }
        else if (ptDelta.x() <= 0 && ptDelta.y() >= 0)
        {
            // 第三象限
            pt = QPoint(ptGlobalOwnerCenter.x() + m_oTipBoxParam.m_wgtOwner->width()/2,
                            ptGlobalOwnerCenter.y() - m_oTipBoxParam.m_wgtOwner->height()/2);
            pt += QPoint(-this->width()/2, -this->height());
        }
        else if (ptDelta.x() >= 0 && ptDelta.y() >= 0)
        {
            // 第四象限
            pt = QPoint(ptGlobalOwnerCenter.x() - m_oTipBoxParam.m_wgtOwner->width()/2,
                        ptGlobalOwnerCenter.y() - m_oTipBoxParam.m_wgtOwner->height()/2);
            pt += QPoint(-this->width()/2, -this->height());
        }

        // 超出屏幕范围的校准
        QRect rcThis(pt, pt + QPoint(this->width(), this->height()));
        QRect rcScreen = QApplication::desktop()->screenGeometry();

        if (!rcScreen.contains(rcThis.topLeft()))
        {
            int nXOffset = rcThis.topLeft().x() - rcScreen.topLeft().x();
            int nYOffset = rcThis.topLeft().y() - rcScreen.topLeft().y();

            if (nXOffset < 0)
            {
                pt.setX(pt.x() - nXOffset);
            }

            if (nYOffset < 0)
            {
                pt.setY(pt.y() - nYOffset);
            }
        }
        else if (!rcScreen.contains(rcThis.topRight()))
        {
            int nXOffset = rcThis.topRight().x() - rcScreen.topRight().x();
            int nYOffset = rcThis.topRight().y() - rcScreen.topRight().y();

            if (nXOffset > 0)
            {
                pt.setX(pt.x() - nXOffset);
            }

            if (nYOffset < 0)
            {
                pt.setY(pt.y() - nYOffset);
            }
        }
        else if (!rcScreen.contains(rcThis.bottomLeft()))
        {
            int nXOffset = rcThis.bottomLeft().x() - rcScreen.bottomLeft().x();
            int nYOffset = rcThis.bottomLeft().y() - rcScreen.bottomLeft().y();

            if (nXOffset < 0)
            {
                pt.setX(pt.x() - nXOffset);
            }

            if (nYOffset > 0)
            {
                pt.setY(pt.y() - nYOffset);
            }
        }
        else if (!rcScreen.contains(rcThis.bottomRight()))
        {
            int nXOffset = rcThis.bottomRight().x() - rcScreen.bottomRight().x();
            int nYOffset = rcThis.bottomRight().y() - rcScreen.bottomRight().y();

            if (nXOffset > 0)
            {
                pt.setX(pt.x() - nXOffset);
            }

            if (nYOffset > 0)
            {
                pt.setY(pt.y() - nYOffset);
            }
        }

    } while(0);

    return pt;
}
Example #3
0
void KxMenuItemWidget::paintEvent(QPaintEvent *event)
{
    // Do not draw invisible menu items
    if(!fMenuItem->isVisible()) return;

    QStylePainter painter(this);
    QStyleOptionMenuItem opt = getStyleOption();
    QRect boxRect;
    bool inOptionBox = false;

    QWidget *q = parentWidget();

    const int hmargin = q->style()->pixelMetric(QStyle::PM_MenuDesktopFrameWidth, 0, q),
        iconWidth = q->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q);

    if(!fMenuItem->isSeparator()) {
        if(fMenuItem->hasOptionBox()) {
            boxRect.setRect(rect().right() - hmargin - iconWidth, rect().top(), iconWidth, rect().height());
            QPoint p = QCursor::pos();
            p = mapFromGlobal(p);
            if(boxRect.contains(p)) {
                inOptionBox = true;
            } else {
                // Subtract option box rect from style option rect
                int newRight = opt.rect.right() - iconWidth - hmargin;
                opt.rect.setRight(newRight);
            }
        }
    }
    // Draw general menu item
    opt.rect.adjust(0, 0, -1, 0);
    painter.drawControl(QStyle::CE_MenuItem, opt);
    // Draw shortcut
    QKeySequence shortcutSeq = fMenuItem->shortcut();
    if(!shortcutSeq.isEmpty()) {
        // shortcut bounds
        QRect scRect = opt.rect;
        QString shortcut = shortcutSeq.toString(QKeySequence::NativeText);
        QMenu *menu = qobject_cast<QMenu *>(parentWidget());
        Q_ASSERT(menu != NULL);
        int shortcutWidth = 12;	// default value in case there is no font
        if ( menu ) {
            QFontMetrics metrics(fMenuItem->font().resolve(menu->font()));
            shortcutWidth = metrics.width(shortcut);
        }
        scRect.setLeft(scRect.right() - shortcutWidth);
        if(inOptionBox || !fMenuItem->hasOptionBox()) {
            scRect.translate(-iconWidth, 0);
        }
        scRect.translate(-kShortcutRightMargin, 0);
        painter.drawItemText(scRect, Qt::AlignRight | Qt::AlignVCenter, palette(), true, shortcut);
    }
    // Draw option box
    if(!fMenuItem->isSeparator() && fMenuItem->hasOptionBox()) {
        QIcon* boxIcon = NULL;
        QVariant v = fMenuItem->optionBoxAction()->property( "optionBoxIcon" );
        if ( v.isValid() ) {
            QString optionBoxIcon;
            optionBoxIcon = v.toString();
            boxIcon = KxQtHelper::createIcon( optionBoxIcon );
        }
        if ( boxIcon == NULL ) {
            boxIcon = new QIcon(":/optionBox.png");
        }
        boxRect.setRect(rect().right() - hmargin - iconWidth, rect().top()+(rect().height()-iconWidth)/2, iconWidth, iconWidth);
        boxIcon->paint(&painter, boxRect, Qt::AlignCenter, fMenuItem->isEnabled() ? QIcon::Normal : QIcon::Disabled);
        delete boxIcon;
    }
}
void LineProfileTool::calculateLineProfile(const QPoint& start, const QPoint& end)
{
	QRect rect = d_target->geometry();
	if (!rect.contains(start) || !rect.contains(end)){
		QMessageBox::warning(d_graph, tr("QtiPlot - Pixel selection warning"),
				tr("Please select the end line point inside the image rectangle!"));
		return;
	}

	QPoint o = d_target->pos();
	QPixmap pic = d_target->pixmap();
	QImage image = pic.convertToImage();

	int x1 = start.x()-o.x();
	int x2 = end.x()-o.x();
	int y1 = start.y()-o.y();
	int y2 = end.y()-o.y();

	QSize realSize = pic.size();
	QSize actualSize = d_target->size();

	if (realSize != actualSize){
		double ratioX = (double)realSize.width()/(double)actualSize.width();
		double ratioY = (double)realSize.height()/(double)actualSize.height();
		x1 = int(x1*ratioX);
		x2 = int(x2*ratioX);
		y1 = int(y1*ratioY);
		y2 = int(y2*ratioY);
	}

	QString text = tr("pixel") + "\tx\ty\t" + tr("intensity") + "\n";

	//uses the fast Bresenham's line-drawing algorithm
#define sgn(x) ((x<0)?-1:((x>0)?1:0))
	int i = 0, n = 0;
	int dx = x2 - x1;      //the horizontal distance of the line
	int dy = y2 - y1;      //the vertical distance of the line
	int dxabs = abs(dx);
	int dyabs = abs(dy);
	int sdx = sgn(dx);
	int sdy = sgn(dy);
	int x = dyabs >> 1;
	int y = dxabs >> 1;
	int px = x1;
	int py = y1;

	if (dxabs>=dyabs){ //the line is more horizontal than vertical
		for(i=0;i<dxabs;i++){
			y+=dyabs;
			if (y>=dxabs){
				y-=dxabs;
				py+=sdy;
			}
			px+=sdx;

			n=dxabs;
			text+=QString::number(i)+"\t";
			text+=QString::number(px)+"\t";
			text+=QString::number(py)+"\t";
			text+=QString::number(averageImagePixel(image, px, py, true))+"\n";
		}
	} else {// the line is more vertical than horizontal
		for(i=0;i<dyabs;i++){
			x+=dxabs;
			if (x>=dyabs){
				x-=dyabs;
				px+=sdx;
			}
			py+=sdy;

			n=dyabs;
			text+=QString::number(i)+"\t";
			text+=QString::number(px)+"\t";
			text+=QString::number(py)+"\t";
			text+=QString::number(averageImagePixel(image, px, py, false))+"\n";
		}
	}

	Table *t = d_app->newTable(tr("Table") + "1", n, 4, text);
	MultiLayer* plot = d_app->multilayerPlot(t, QStringList(QString(t->objectName())+"_intensity"), 0);
	Graph *g = (Graph*)plot->activeLayer();
	if (g){
		g->setTitle("");
		g->setXAxisTitle(tr("pixels"));
		g->setYAxisTitle(tr("pixel intensity (a.u.)"));
	}

}
Example #5
0
void RulerT::mouseMoveEvent(QMouseEvent *m)
{
	double oldInd;
	QRect fpo;
	if ((mousePressed) && (m->y() < height()) && (m->y() > 0) && (m->x() > 0) && (m->x() < width()))
	{
		qApp->changeOverrideCursor(QCursor(Qt::SizeHorCursor));
		switch (rulerCode)
		{
			case 1:
				firstLine -= mouseX - m->x();
				if (firstLine+leftIndent+offset < offset)
					firstLine += mouseX - m->x();
				if (firstLine+leftIndent > Width)
					firstLine  = Width-leftIndent;
				emit firstLineMoved(firstLine);
				repaint();
				break;
			case 2:
				oldInd = leftIndent+firstLine;
				leftIndent -= mouseX - m->x();
				if (leftIndent < 0)
					leftIndent = 0;
				if (leftIndent > Width-1)
					leftIndent  = Width-1;
				firstLine = oldInd - leftIndent;
				emit leftIndentMoved(leftIndent);
				emit firstLineMoved(firstLine);
				repaint();
				break;
			case 3:
				tabValues[actTab].tabPosition -= mouseX - m->x();
				if (tabValues[actTab].tabPosition < 0)
					tabValues[actTab].tabPosition = 0;
				if (tabValues[actTab].tabPosition > Width-1)
					tabValues[actTab].tabPosition = Width-1;
				updateTabList();
				emit tabMoved(tabValues[actTab].tabPosition);
				repaint();
				break;
			default:
				break;
		}
		mouseX = m->x();
		return;
	}
	if ((!mousePressed) && (m->y() < height()) && (m->y() > 0) && (m->x() > 0) && (m->x() < width()))
	{
		qApp->changeOverrideCursor(QCursor(loadIcon("tab.png"), 3));
		if (haveInd)
		{
			fpo = QRect(static_cast<int>(firstLine+leftIndent-offset)-4, 0, 8, 12);
			if (fpo.contains(m->pos()))
			{
				qApp->changeOverrideCursor(QCursor(Qt::SizeHorCursor));
				return;
			}
			fpo = QRect(static_cast<int>(leftIndent-offset)-4, 12, 8, 12);
			if (fpo.contains(m->pos()))
			{
				qApp->changeOverrideCursor(QCursor(Qt::SizeHorCursor));
				return;
			}
		}
		if (tabValues.count() != 0)
		{
			for (int yg = 0; yg < static_cast<int>(tabValues.count()); yg++)
			{
				fpo = QRect(static_cast<int>(tabValues[yg].tabPosition-offset)-3, 15, 8, 8);
				if (fpo.contains(m->pos()))
				{
					qApp->changeOverrideCursor(QCursor(Qt::SizeHorCursor));
					return;
				}
			}
		}
	}
}
Example #6
0
/*!
    \reimp
 */
void QxtSpanSlider::mouseMoveEvent(QMouseEvent* event)
{
    if (qxt_d().lowerPressed != QStyle::SC_SliderHandle && qxt_d().upperPressed != QStyle::SC_SliderHandle)
    {
        event->ignore();
        return;
    }

    QStyleOptionSlider opt;
    qxt_d().initStyleOption(&opt);
    const int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &opt, this);
    int newPosition = qxt_d().pixelPosToRangeValue(qxt_d().pick(event->pos()) - qxt_d().offset);
    if (m >= 0)
    {
        const QRect r = rect().adjusted(-m, -m, m, m);
        if (!r.contains(event->pos()))
        {
            newPosition = qxt_d().position;
        }
    }

    // pick the preferred handle on the first movement
    if (qxt_d().firstMovement)
    {
        if (qxt_d().lower == qxt_d().upper)
        {
            if (newPosition < lowerValue())
            {
                qxt_d().swapControls();
                qxt_d().firstMovement = false;
            }
        }
        else
        {
            qxt_d().firstMovement = false;
        }
    }

    if (qxt_d().lowerPressed == QStyle::SC_SliderHandle)
    {
        if (qxt_d().movement == NoCrossing)
            newPosition = qMin(newPosition, upperValue());
        else if (qxt_d().movement == NoOverlapping)
            newPosition = qMin(newPosition, upperValue() - 1);

        if (qxt_d().movement == FreeMovement && newPosition > qxt_d().upper)
        {
            qxt_d().swapControls();
            setUpperPosition(newPosition);
        }
        else
        {
            setLowerPosition(newPosition);
        }
    }
    else if (qxt_d().upperPressed == QStyle::SC_SliderHandle)
    {
        if (qxt_d().movement == NoCrossing)
            newPosition = qMax(newPosition, lowerValue());
        else if (qxt_d().movement == NoOverlapping)
            newPosition = qMax(newPosition, lowerValue() + 1);

        if (qxt_d().movement == FreeMovement && newPosition < qxt_d().lower)
        {
            qxt_d().swapControls();
            setLowerPosition(newPosition);
        }
        else
        {
            setUpperPosition(newPosition);
        }
    }
    event->accept();
}
bool PluginItemDelegate::editorEvent( QEvent *event,
                                      QAbstractItemModel *model,
                                      const QStyleOptionViewItem &option,
                                      const QModelIndex &index )
{
    Q_ASSERT(event);
    Q_ASSERT(model);

    if ( ( event->type() == QEvent::MouseButtonRelease )
         || ( event->type() == QEvent::MouseButtonDblClick )
         || ( event->type() == QEvent::MouseButtonPress )
         || ( event->type() == QEvent::MouseMove ) )
    {
        QMouseEvent *me = static_cast<QMouseEvent*>(event);
        QPoint mousePosition = me->pos() - option.rect.topLeft();

        if ( ( event->type() == QEvent::MouseMove )
             && !( me->buttons() & Qt::LeftButton ) )
        {
            // If the mouse moves around and no left button is pressed, no pushbutton is pressed
            // and no other event will be successful.
            m_aboutPressedIndex = QModelIndex();
            m_configPressedIndex = QModelIndex();
            return true;
        }

        // Handle checkbox
        QRect checkRect = checkboxOption( option, index, 0, Qt::AlignLeft ).rect;
        if ( checkRect.contains( mousePosition )
             && ( ( event->type() == QEvent::MouseButtonDblClick )
                   || ( event->type() == QEvent::MouseButtonRelease ) ) )
        {
            // make sure that the item is checkable
            Qt::ItemFlags flags = model->flags(index);
            if ( !( flags & Qt::ItemIsUserCheckable ) || !( option.state & QStyle::State_Enabled )
                || !( flags & Qt::ItemIsEnabled ) )
                return false;

            // make sure that we have a check state
            QVariant checkValue = index.data( Qt::CheckStateRole );
            if ( !checkValue.isValid() )
                return false;

            // eat the double click events inside the check rect
            if ( event->type() == QEvent::MouseButtonDblClick )
                return true;

            Qt::CheckState state = ( static_cast<Qt::CheckState>( checkValue.toInt() ) == Qt::Checked
                                     ? Qt::Unchecked : Qt::Checked );
            return model->setData(index, state, Qt::CheckStateRole);
        }

        if ( ( event->type() == QEvent::MouseMove )
             && !( me->buttons() & Qt::LeftButton ) )
        {
            m_aboutPressedIndex = QModelIndex();
            m_configPressedIndex = QModelIndex();
            return true;
        }

        QPoint topRight = option.rect.topRight();

        // Handle aboutButton
        {
            QRect aboutRect = buttonOption( option,
                                            index,
                                            PluginItemDelegate::About,
                                            topRight.x(),
                                            Qt::AlignRight ).rect;
            if ( aboutRect.contains( mousePosition ) ) {
                if ( event->type() == QEvent::MouseButtonDblClick )
                    return true;
                if ( event->type() == QEvent::MouseButtonPress ) {
                    m_aboutPressedIndex = index;
                    m_configPressedIndex = QModelIndex();
                    return true;
                }
                if ( event->type() == QEvent::MouseButtonRelease ) {
                    m_aboutPressedIndex = QModelIndex();
                    m_configPressedIndex = QModelIndex();
                    emit aboutPluginClicked( index );
                    return true;
                }
                if ( event->type() == QEvent::MouseMove ) {
                    if ( me->buttons() & Qt::LeftButton ) {
                        m_aboutPressedIndex = index;
                        m_configPressedIndex = QModelIndex();
                        return true;
                    }
                    else {
                        m_aboutPressedIndex = QModelIndex();
                        m_configPressedIndex = QModelIndex();
                        return true;
                    }
                }
            }
            else {
                // If the mouse is on the item and the mouse isn't above the button.
                // no about button is pressed.
                m_aboutPressedIndex = QModelIndex();
            }
            topRight -= QPoint( aboutRect.width(), 0 );
        }

        // Handle configButton
        // make sure we have config button
        if ( index.data( RenderPluginModel::ConfigurationDialogAvailable ).toBool() ) {
            QRect configRect = buttonOption( option,
                                             index,
                                             PluginItemDelegate::Configure,
                                             topRight.x(),
                                             Qt::AlignRight ).rect;
            if( configRect.contains( mousePosition ) ) {
                if ( event->type() == QEvent::MouseButtonDblClick )
                    return true;

                if ( event->type() == QEvent::MouseButtonPress ) {
                    m_aboutPressedIndex = QModelIndex();
                    m_configPressedIndex = index;
                    return true;
                }
                if ( event->type() == QEvent::MouseButtonRelease ) {
                    m_aboutPressedIndex = QModelIndex();
                    m_configPressedIndex = QModelIndex();
                    emit configPluginClicked( index );
                    return true;
                }
                if ( event->type() == QEvent::MouseMove ) {
                    if ( me->buttons() & Qt::LeftButton ) {
                        m_aboutPressedIndex = QModelIndex();
                        m_configPressedIndex = index;
                        return true;
                    }
                    else {
                        m_aboutPressedIndex = QModelIndex();
                        m_configPressedIndex = QModelIndex();
                        return true;
                    }
                }
            }
            else {
                // If the mouse is on the item and the mouse isn't above the button.
                // no config button is pressed.
                m_configPressedIndex = QModelIndex();
            }

            topRight -= QPoint( configRect.width(), 0 );
        }
        else {
            // If we don't have an config dialog shown and the mouse is over this item,
            // no config button is pressed.
            m_configPressedIndex = QModelIndex();
        }
    }

    return false;
}
Example #8
0
bool BridgesDelegate::editorEvent( QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index ) {
	Q_ASSERT(event);
	Q_ASSERT(model);

	// Always reset the ad-hoc group modify flag.
	if (event->type() == QEvent::MouseButtonRelease)
	{
		opaqueGroupModify_ = false;
	}

	// Make sure that the item is checkable.
	Qt::ItemFlags flags = model->flags(index);

	if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
	{
		return false;
	}

	// Make sure that we have a check state.
	QVariant value = index.data(Qt::CheckStateRole);

	if (!value.isValid())
	{
		return false;
	}

    Qt::CheckState newState = static_cast<Qt::CheckState>(value.toInt());

	// Handle the mouse button events.
	if (event->type() == QEvent::MouseButtonPress)
	{
		const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

		QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
			option.decorationSize,
			QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
			option.rect.width() - (2 * textMargin),
			option.rect.height()));

		if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
		{
			return false;
		}

		newState = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked ? Qt::Unchecked : Qt::Checked);
		opaqueGroupModify_ = true;
		opaque = newState;
	}
	else if (event->type() == QEvent::MouseMove)
	{
		if (!opaqueGroupModify_ || static_cast<Qt::CheckState>(value.toInt()) == opaque)
		{
			return false;
		}

		const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

		QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
			option.decorationSize,
			QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
			option.rect.width() - (2 * textMargin),
			option.rect.height()));

		if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
		{
			return false;
		}

		newState = opaque;
	}
	else if (event->type() == QEvent::KeyPress)
	{
		if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space &&
			static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
		{
			return false;
		}
	}
	else
	{
		return false;
	}

	return model->setData(index, newState, Qt::CheckStateRole);
}
Example #9
0
int Hruler::findRulerHandle(QPoint mp, double grabRadius)
{
	int mx = mp.x();
	QRect fpo;
	
	int result = rc_none;
	
	int Pos = textPosToLocal(0);
	if (Pos-1 < (mx + grabRadius) && Pos-1 > (mx - grabRadius))
		result = rc_leftFrameDist;
	
	Pos = textPosToLocal(textWidth());
	if (Pos+1 < (mx + grabRadius) && Pos+1 > (mx - grabRadius))
		result = rc_rightFrameDist;
	
	double ColWidth = (textWidth() - ColGap * (Cols - 1)) / Cols;
	
	ActCol = 0;
	for (int CurrCol = 0; CurrCol < Cols; ++CurrCol)
	{
		Pos = textPosToLocal((ColWidth+ColGap)*CurrCol);
		fpo = QRect(Pos, topline, static_cast<int>(ColWidth*Scaling), rulerheight);
		if (fpo.contains(mp))
		{
			ActCol = CurrCol+1;
			break;
		}
	}
	if (ActCol == 0)
	{
		ActCol = 1;
		return result;
	}
	
	Pos = textPosToLocal(First+Indent+(ColWidth+ColGap)*(ActCol-1));
	fpo = QRect(Pos-1, topline, grabRadius+1, rulerheight/2);
	if (fpo.contains(mp))
	{
		return rc_indentFirst;
	}
	Pos = textPosToLocal(Indent+(ColWidth+ColGap)*(ActCol-1));
	fpo = QRect(Pos-1, midline, grabRadius+1, rulerheight/2);
	if (fpo.contains(mp))
	{
		return rc_leftMargin;
	}
	Pos = textPosToLocal(RMargin+(ColWidth+ColGap)*(ActCol-1));
	fpo = QRect(Pos-grabRadius, midline, grabRadius, rulerheight/2);
	if (fpo.contains(mp))
	{
		return rc_rightMargin;
	}
	if (TabValues.count() != 0)
	{
		for (int yg = 0; yg < signed(TabValues.count()); yg++)
		{
			Pos = textPosToLocal(TabValues[yg].tabPosition+(ColWidth+ColGap)*(ActCol-1));
			fpo = QRect(Pos-grabRadius, tabline, 2*grabRadius, rulerheight/2 + 2);
			if (fpo.contains(mp))
			{
				result = rc_tab;
				ActTab = yg;
				break;
			}
		}
	}
	return result;
}
Example #10
0
void XWidget::showEvent(QShowEvent *event)
{
  if(!_private->_shown)
  {
    _private->_shown = true;
    if (windowFlags() & (Qt::Window | Qt::Dialog))
    {
      QRect availableGeometry = QApplication::desktop()->availableGeometry();
      if(!omfgThis->showTopLevel() && !isModal())
        availableGeometry = QRect(QPoint(0, 0), omfgThis->workspace()->size());

      QSettings settings(QSettings::UserScope, "OpenMFG.com", "OpenMFG");
      QString objName = objectName();
      QPoint pos = settings.value(objName + "/geometry/pos").toPoint();
      QSize lsize = settings.value(objName + "/geometry/size").toSize();

      if(lsize.isValid() && settings.value(objName + "/geometry/rememberSize", true).toBool())
        resize(lsize);

      setAttribute(Qt::WA_DeleteOnClose);
      if(omfgThis->showTopLevel() || isModal())
      {
        omfgThis->_windowList.append(this);
        QRect r(pos, size());
        if(!pos.isNull() && availableGeometry.contains(r) && settings.value(objName + "/geometry/rememberPos", true).toBool())
          move(pos);
      }
      else
      {
        QWidget * fw = focusWidget();
        omfgThis->workspace()->addWindow(this);
        QRect r(pos, size());
        if(!pos.isNull() && availableGeometry.contains(r) && settings.value(objName + "/geometry/rememberPos", true).toBool() && parentWidget())
          parentWidget()->move(pos);
        // This originally had to be after the show? Will it work here?
        if(fw)
          fw->setFocus();
      }
    }

    QStringList parts = objectName().split(" ");
    QStringList search_parts;
    QString oName;
    while(!parts.isEmpty())
    {
      search_parts.append(parts.takeFirst());
      oName = search_parts.join(" ");
      // load and run an QtScript that applies to this window
      qDebug() << "Looking for a script on window " << oName;
      q.prepare("SELECT script_source, script_order"
                "  FROM script"
                " WHERE((script_name=:script_name)"
                "   AND (script_enabled))"
                " ORDER BY script_order;");
      q.bindValue(":script_name", oName);
      q.exec();
      while(q.next())
      {
        QString script = q.value("script_source").toString();
        if(!_private->_engine)
        {
          _private->_engine = new QScriptEngine();
          omfgThis->loadScriptGlobals(_private->_engine);
          QScriptValue mywindow = _private->_engine->newQObject(this);
          _private->_engine->globalObject().setProperty("mywindow", mywindow);
        }
  
        QScriptValue result = _private->_engine->evaluate(script);
        if (_private->_engine->hasUncaughtException())
        {
          int line = _private->_engine->uncaughtExceptionLineNumber();
          qDebug() << "uncaught exception at line" << line << ":" << result.toString();
        }
      }
    }
  }
  QWidget::showEvent(event);
}
void LuminanceRangeWidget::paintEvent( QPaintEvent *pe )
{
  {  
  QPainter p( this );

  QRect fRect = getPaintRect();

  if( fRect.width() < 50 )      // Does not make sense to paint anything
    return;

  // Paint range window
  {
    int x1, x2;
    x1 = getWindowX( draggedMin() );
    x2 = getWindowX( draggedMax() );
    QColor selectionColor = mouseDragStart == DRAGNOTSTARTED ?
      QColor( 0, 100, 255 ) : QColor( 0, 150, 255 );
    p.fillRect( x1, fRect.top(), x2-x1, fRect.height(), QBrush( selectionColor ) );
  }

  // Paint histogram
  if( histogramImage != NULL ) {
    if( histogram == NULL || histogram->getBins() != fRect.width() ) {
      delete histogram;
      // Build histogram from at least 5000 pixels
      int accuracy = histogramImage->getRows()*histogramImage->getCols()/5000;
      if( accuracy < 1 ) accuracy = 1;
      histogram = new Histogram( fRect.width(), accuracy );
      histogram->computeLog( histogramImage, minValue, maxValue );
    }
    
    float maxP = histogram->getMaxP();
    int i = 0;
    p.setPen( Qt::green );
    for( int x = fRect.left(); i < histogram->getBins(); x++, i++ ) {
      if( histogram->getP(i) > 0 ) {
        int barSize = (int)((float)fRect.height() * histogram->getP(i)/maxP);
        p.drawLine( x, fRect.bottom(), x, fRect.bottom() - barSize );
      }
      
    }
    
  }

  // Paint scale
  QFont labelFont( "SansSerif", 8 );
  p.setFont( labelFont );
  p.setPen( Qt::black );
  QRect textBounding = p.boundingRect( fRect, Qt::AlignHCenter|Qt::AlignBottom, "-8" );
  for( float x = ceil( minValue ); x <= floor( maxValue ); x++ ) {
    int rx = getWindowX(x);
    p.drawLine( rx, fRect.top(), rx, textBounding.top() );
    char str[10];
    sprintf( str, "%g", x );
    p.drawText( rx-20, textBounding.top(), 40, textBounding.height(),
      Qt::AlignHCenter|Qt::AlignBottom, str );
  }


  // Paint value pointer
  if( showVP )
  {
    int x = getWindowX( valuePointer );
    if( fRect.contains( x, fRect.y() ) ) {
      p.setPen( Qt::yellow );
      p.drawLine( x, fRect.top(), x, fRect.bottom() );
    }
    
  }
  
}
  QFrame::paintEvent(pe);  
}
Example #12
0
void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event)
{
    Q_Q(QDockWidget);

    int fw = q->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, 0, q);

    QRect geo = q->geometry();
    QRect titleRect = q->frameGeometry();
#ifdef Q_WS_MAC
    if ((features & QDockWidget::DockWidgetVerticalTitleBar)) {
        titleRect.setTop(geo.top());
        titleRect.setBottom(geo.bottom());
        titleRect.setRight(geo.left() - 1);
    } else
#endif
    {
        titleRect.setLeft(geo.left());
        titleRect.setRight(geo.right());
        titleRect.setBottom(geo.top() - 1);
        titleRect.adjust(0, fw, 0, 0);
    }

    switch (event->type()) {
        case QEvent::NonClientAreaMouseButtonPress:
            if (!titleRect.contains(event->globalPos()))
                break;
            if (state != 0)
                break;
            if (qobject_cast<QMainWindow*>(parent) == 0)
                break;
            if (isAnimating())
                break;
            initDrag(event->pos(), true);
            if (state == 0)
                break;
#ifdef Q_OS_WIN
            // On Windows, NCA mouse events don't contain modifier info
            state->ctrlDrag = GetKeyState(VK_CONTROL) & 0x8000;
#else
            state->ctrlDrag = event->modifiers() & Qt::ControlModifier;
#endif
            startDrag();
            break;
        case QEvent::NonClientAreaMouseMove:
            if (state == 0 || !state->dragging)
                break;
            if (state->nca) {
                endDrag();
            }
#ifdef Q_OS_MAC
            else { // workaround for lack of mouse-grab on Mac
                QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q->parentWidget()));
                Q_ASSERT(layout != 0);

                q->move(event->globalPos() - state->pressPos);
                if (!state->ctrlDrag)
                    layout->hover(state->widgetItem, event->globalPos());
            }
#endif
            break;
        case QEvent::NonClientAreaMouseButtonRelease:
#ifdef Q_OS_MAC
                        if (state)
                                endDrag();
#endif
                        break;
        case QEvent::NonClientAreaMouseButtonDblClick:
            _q_toggleTopLevel();
            break;
        default:
            break;
    }
}
Example #13
0
void XDialog::showEvent(QShowEvent *event)
{
  if(!_private->_shown)
  {
    _private->_shown = true;

    QRect availableGeometry = QApplication::desktop()->availableGeometry();

    QString objName = objectName();
    QPoint pos = xtsettingsValue(objName + "/geometry/pos").toPoint();
    QSize lsize = xtsettingsValue(objName + "/geometry/size").toSize();

    if(lsize.isValid() && xtsettingsValue(objName + "/geometry/rememberSize", true).toBool())
      resize(lsize);

    // do I want to do this for a dialog?
    //_windowList.append(w);
    QRect r(pos, size());
    if(!pos.isNull() && availableGeometry.contains(r) && xtsettingsValue(objName + "/geometry/rememberPos", true).toBool())
      move(pos);

    _private->_rememberPos = new QAction(tr("Remember Posisition"), this);
    _private->_rememberPos->setCheckable(true);
    _private->_rememberPos->setChecked(xtsettingsValue(objectName() + "/geometry/rememberPos", true).toBool());
    connect(_private->_rememberPos, SIGNAL(triggered(bool)), this, SLOT(setRememberPos(bool)));
    _private->_rememberSize = new QAction(tr("Remember Size"), this);
    _private->_rememberSize->setCheckable(true);
    _private->_rememberSize->setChecked(xtsettingsValue(objectName() + "/geometry/rememberSize", true).toBool());
    connect(_private->_rememberSize, SIGNAL(triggered(bool)), this, SLOT(setRememberSize(bool)));

    addAction(_private->_rememberPos);
    addAction(_private->_rememberSize);
    setContextMenuPolicy(Qt::ActionsContextMenu);

    QStringList parts = objectName().split(" ");
    QStringList search_parts;
    QString oName;
    while(!parts.isEmpty())
    {
      search_parts.append(parts.takeFirst());
      oName = search_parts.join(" ");

      // load and run an QtScript that applies to this window
      qDebug() << "Looking for a script on dialog " << oName;
      q.prepare("SELECT script_source, script_order"
                "  FROM script"
                " WHERE((script_name=:script_name)"
                "   AND (script_enabled))"
                " ORDER BY script_order;");
      q.bindValue(":script_name", oName);
      q.exec();
      while(q.next())
      {
        QString script = scriptHandleIncludes(q.value("script_source").toString());
        if(!_private->_engine)
        {
          _private->_engine = new QScriptEngine();
          omfgThis->loadScriptGlobals(_private->_engine);
          QScriptValue mywindow = _private->_engine->newQObject(this);
          _private->_engine->globalObject().setProperty("mywindow", mywindow);
        }
  
        QScriptValue result = _private->_engine->evaluate(script, objectName());
        if (_private->_engine->hasUncaughtException())
        {
          int line = _private->_engine->uncaughtExceptionLineNumber();
          qDebug() << "uncaught exception at line" << line << ":" << result.toString();
        }
      }
    }
  }
Example #14
0
QRect QTabContainer::findDropRect(const QPoint& globalPos, int tabWidth, QTabFramework::InsertPolicy& insertPolicy, QRect& tabRectResult, int& tabIndex)
{
  QPoint pos = mapFromGlobal(globalPos);
  QRect containerRect = rect();
  QRect result;
  tabIndex = -1;
  if(containerRect.contains(pos))
  {
    if(count() == 0)
    {
      insertPolicy = QTabFramework::InsertOnTop;
      result = containerRect;
    }
    else if(tabBar()->geometry().contains(pos))
    {
      insertPolicy = QTabFramework::Insert;
      result = containerRect;
      QTabBar* tabBar = this->tabBar();
      for(int i = 0, count = tabBar->count(); i < count; ++i)
      {
        QRect tabRect = tabBar->tabRect(i);
        if(tabRect.contains(pos))
        {
          tabRectResult = tabRect;
          tabRectResult.setRight(tabRect.left() + tabWidth);
          tabRectResult.translate(tabBar->mapToGlobal(QPoint(0, 0)));
          tabIndex = i;
          break;
        }
      }
    }
    else if(pos.x() < containerRect.x() + containerRect.width() / 3)
    {
      insertPolicy = QTabFramework::InsertLeft;
      result = QRect(containerRect.topLeft(), QPoint(containerRect.x() + containerRect.width() / 3, containerRect.bottom()));
    }
    else if(pos.x() >= containerRect.x() + containerRect.width() * 2 / 3)
    {
      insertPolicy = QTabFramework::InsertRight;
      result = QRect(QPoint(containerRect.x() + containerRect.width() * 2 / 3, containerRect.y()), containerRect.bottomRight());
    }
    else if(pos.y() < containerRect.y() + tabBar()->geometry().height())
    {
      insertPolicy = QTabFramework::Insert;
      result = containerRect;
      tabIndex = this->tabBar()->count();
    }
    else if(pos.y() < containerRect.y() + containerRect.height() / 3)
    {
      insertPolicy = QTabFramework::InsertTop;
      result = QRect(containerRect.topLeft(), QPoint(containerRect.right(), containerRect.y() + containerRect.height() / 3));
    }
    else if(pos.y() >= containerRect.y() + containerRect.height() * 2 / 3)
    {
      insertPolicy = QTabFramework::InsertBottom;
      result = QRect(QPoint(containerRect.x(), containerRect.y() + containerRect.height() * 2 / 3), containerRect.bottomRight());
    }
    else
    {
      insertPolicy = QTabFramework::InsertOnTop;
      result = containerRect;
    }
  }
  else
  {
    insertPolicy = QTabFramework::InsertFloating;
    return QRect();
  }
  result.translate(mapToGlobal(QPoint(0, 0)));
  return result;
}
Example #15
0
void LapUSMainWindow::mouseMoved(int x,int y){

	//std::cout<<"Mouse moved\n";
	QMouseEvent* event = new QMouseEvent(QEvent::MouseMove,QCursor::pos (),Qt::LeftButton,0,0);
	QPoint mousePos = QCursor::pos();

	QRect browserRect = browserWidget->geometry();
	if(browserRect.contains(mousePos)){
		//std::cout<<"Da Vinci moving in browser widget\n";
	

    QListWidgetItem* item = NULL, *oldItem = NULL;
	 if(browserWidget->currentIndex() == 0){

          //cout << "The scroll var value "<<browserWidget->list->verticalScrollBar()->value()<<"\n";

//         std::cout<<"Da vinci cursor moving in the US browser..\n";
         item = browserWidget->list->itemAt(browserWidget->mapFromGlobal(QCursor::pos()));
         oldItem = browserWidget->list->itemAt(browserWidget->mapFromGlobal(oldPos));


//         browserWidget->list->scrollToItem(item);
         // update only if the current item is not same as the old item TODO 
		 if(item && (item == oldItem)){
			// std::cout<<"Mouse still on the old item \n";
		 }
		 if(item && (item != oldItem)){
			std::cout<<"Mouse on a different item \n";

            std::cout<<"US Item found \n";
            this->showItem(item);

            browserWidget->list->setCurrentItem(item);
          }
            int dx = oldPos.x() - x;
            int dy = oldPos.y() -y ;
            if(clicked && !released){

            	int oldValue = browserWidget->list->verticalScrollBar()->value();
            	//cout << "The scroll var value "<<browserWidget->list->verticalScrollBar()->value()<<"\n";
				browserWidget->list->verticalScrollBar()->setValue(oldValue- (2 * dy));

			// 	browserWidget->list->scrollToItem(item,QAbstractItemView::PositionAtCenter);
        }
    }   
    else if(browserWidget->currentIndex() == 1){
        std::cout<<"Da vinci cursor moving in the preop browser..\n";
        item = browserWidget->list2->itemAt(browserWidget->mapFromGlobal(QCursor::pos()));  // change this TODO BAD programming 

        if(item){
            std::cout<<"Preop Item found \n";
            this->showItemPreop(item);
            browserWidget->list2->setCurrentItem(item);
            //Q_EMIT updatePreopImage(item);

 
        }

        //BAD  make API's in Browser widget
        int dx = oldPos.x() - x;
        int dy = oldPos.y() -y ;
        if(clicked && !released){

            	int oldValue = browserWidget->list2->verticalScrollBar()->value();
				browserWidget->list2->verticalScrollBar()->setValue(oldValue- (2 * dy));

			// 	browserWidget->list->scrollToItem(item,QAbstractItemView::PositionAtCenter);
        }
    }
}
		
	oldPos = QPoint(x,y);
	QApplication::postEvent(this,event);
}
/* Timer event processor
 * Handles auto hide feature of the toolbar */
void VBoxMiniToolBar::timerEvent(QTimerEvent *pEvent)
{
    if (pEvent->timerId() == m_scrollTimer.timerId())
    {
        /* Due to X11 async nature, this timer-event could come before parent
         * VM window become visible, we should ignore those timer-events: */
        if (QApplication::desktop()->screenNumber(window()) == -1)
            return;

        /* Update tool-bar position: */
        QRect screen = m_fSeamless ? vboxGlobal().availableGeometry(QApplication::desktop()->screenNumber(window())) :
                                     QApplication::desktop()->screenGeometry(window());
        switch (m_alignment)
        {
            case AlignTop:
            {
                if (((m_iPositionY == screen.y()) && m_fSlideToScreen) ||
                    ((m_iPositionY == screen.y() - height() + 1) && !m_fSlideToScreen))
                {
                    m_scrollTimer.stop();
                    if (m_fHideAfterSlide)
                    {
                        m_fHideAfterSlide = false;
                        hide();
                    }
                    return;
                }
                m_fSlideToScreen ? ++m_iPositionY : --m_iPositionY;
                break;
            }
            case AlignBottom:
            {
                if (((m_iPositionY == screen.y() + screen.height() - height()) && m_fSlideToScreen) ||
                    ((m_iPositionY == screen.y() + screen.height() - 1) && !m_fSlideToScreen))
                {
                    m_scrollTimer.stop();
                    if (m_fHideAfterSlide)
                    {
                        m_fHideAfterSlide = false;
                        hide();
                    }
                    return;
                }
                m_fSlideToScreen ? --m_iPositionY : ++m_iPositionY;
                break;
            }
            default:
                break;
        }
        move(parentWidget()->mapFromGlobal(QPoint(m_iPositionX, m_iPositionY)));
        emit geometryUpdated();
    }
    else if (pEvent->timerId() == m_autoScrollTimer.timerId())
    {
        QRect rect = this->rect();
        QPoint p = mapFromGlobal(QCursor::pos());
        if (!rect.contains(p))
        {
            ++m_iAutoHideCounter;

            if (m_iAutoHideCounter == m_iAutoHideTotalCounter)
            {
                m_fSlideToScreen = false;
                m_scrollTimer.start(m_iScrollDelay, this);
            }
        }
        else
            m_iAutoHideCounter = 0;
    }
    else
        QWidget::timerEvent(pEvent);
}
Example #17
0
void ccHistogramWindow::mouseMoveEvent(QMouseEvent *event)
{
	if (event->buttons() & Qt::LeftButton)
	{
		if (m_sfInteractionMode)
		{
			QPoint mousePos = event->pos();
			if (m_histogram)
			{
				QRect rect = m_histogram->rect();
				mousePos.setX(std::min(rect.x()+rect.width(),std::max(rect.x(),mousePos.x())));
			}

			switch(m_selectedItem)
			{
			case NONE:
				//nothing to do
				break;
			case LEFT_AREA:
				if (m_areaLeft)
				{
					double newValue = m_areaLeft->pixelToKey(mousePos.x());
					if (m_areaRight)
						newValue = std::min(newValue,m_areaRight->currentVal());
					setMinDispValue(newValue);
				}
				break;
			case RIGHT_AREA:
				if (m_areaRight)
				{
					double newValue = m_areaRight->pixelToKey(mousePos.x());
					if (m_areaLeft)
						newValue = std::max(newValue,m_areaLeft->currentVal());
					setMaxDispValue(newValue);
				}
				break;
			case BOTH_AREAS:
				{
					int dx = m_lastMouseClick.x() - mousePos.x();
					if (dx < -2)
					{
						//going to the right
						m_selectedItem = RIGHT_AREA;
						//call the same method again
						mouseMoveEvent(event);
						return;
					}
					else if (dx > 2)
					{
						//going to the left
						m_selectedItem = LEFT_AREA;
						//call the same method again
						mouseMoveEvent(event);
						return;
					}
					//else: nothing we can do right now!
				}
				break;
			case LEFT_ARROW:
				if (m_arrowLeft)
				{
					double newValue = m_arrowLeft->pixelToKey(mousePos.x());
					if (m_arrowRight)
						newValue = std::min(newValue,m_arrowRight->currentVal());
					setMinSatValue(newValue);
				}
				break;
			case RIGHT_ARROW:
				if (m_arrowRight)
				{
					double newValue = m_arrowRight->pixelToKey(mousePos.x());
					if (m_arrowLeft)
						newValue = std::max(newValue,m_arrowLeft->currentVal());
					setMaxSatValue(newValue);
				}
				break;
			case BOTH_ARROWS:
				{
					int dx = m_lastMouseClick.x() - mousePos.x();
					if (dx < -2)
					{
						//going to the right
						m_selectedItem = RIGHT_ARROW;
						//call the same method again
						mouseMoveEvent(event);
						return;
					}
					else if (dx > 2)
					{
						//going to the left
						m_selectedItem = LEFT_ARROW;
						//call the same method again
						mouseMoveEvent(event);
						return;
					}
					//else: nothing we can do right now!
				}
				break;
			default:
				assert(false);
				break;
			}
		}
		else
		{
			if (m_histogram && !m_histoValues.empty())
			{
				QRect roi = m_histogram->rect();
				if (roi.contains(event->pos(),false))
				{
					m_drawVerticalIndicator = true;

					int verticalIndicatorPosition = (static_cast<int>(m_histoValues.size()) * (event->x() - roi.x())) / roi.width();
					m_verticalIndicatorPositionPercent = static_cast<double>(verticalIndicatorPosition) / m_histoValues.size();

					refresh();
				}
			}
		}
	}
	else
	{
		event->ignore();
	}
}
Example #18
0
void ChartWidget::contextMenuEvent(QContextMenuEvent* e)
{
	QRect rcWaveforms = m_rcPixmap;

	ChartPointInfo info;
	QPoint ptPixmap = e->pos() - m_rcPixmap.topLeft();
	m_pixmap->fillChartPointInfo(ptPixmap, &info);
	m_clickInfo = info;
	ViewWaveInfo* vwi = info.vwi;

	m_ptMouseWidget = e->pos();
	m_ptMousePixmap = ptPixmap;
	m_ptClickWidget = m_ptMouseWidget;
	m_ptClickPixmap = m_ptMousePixmap;

	const WaveInfo* wave = NULL;
	if (vwi != NULL)
		wave = vwi->wave();

	QMenu menu(this);
	QAction* actAddPeakEndPoint = NULL;
	QAction* actAddPeakMarker = NULL;
	QAction* actAddTimeMarker = NULL;
	QAction* actRemoveMarker = NULL;
	QAction* actSettings = NULL;
	QAction* actDelete = NULL;
	{
		// Clicked on a chosen peak:
		if (info.iChosenPeak >= 0)
		{
			if (m_chartS->params().task == EadTask_Markers) {
				actRemoveMarker = new QAction(tr("Remove Marker"), &menu);
				menu.addAction(actRemoveMarker);
				if (wave->peaksChosen[info.iChosenPeak].type == MarkerType_EadPeakXY) {
					actAddPeakEndPoint = new QAction(tr("Add End-Point to Marker"), &menu);
					menu.addAction(actAddPeakEndPoint);
				}
			}
		}
		// Clicked on a detected peak:
		else if (info.didxPossiblePeak >= 0)
		{
			actAddPeakMarker = new QAction(tr("Add Peak Marker"), &menu);
			menu.addAction(actAddPeakMarker);
		}
		// Clicked on a wave:
		else if (wave != NULL)
		{
			if (m_chartS->params().task == EadTask_Markers) {
				if (wave->type == WaveType_EAD || wave->type == WaveType_FID) {
					actAddPeakMarker = new QAction(tr("Add Peak Marker"), &menu);
					menu.addAction(actAddPeakMarker);
				}
				actAddTimeMarker = new QAction(tr("Add Time Marker"), &menu);
				menu.addAction(actAddTimeMarker);
			}
			actSettings = new QAction(tr("Settings..."), &menu);
			menu.addAction(actSettings);

			actDelete = new QAction(tr("Delete..."), &menu);
			// Enable if this is not an averaged wave
			actDelete->setEnabled(wave->recId() > 0);
			menu.addAction(actDelete);
		}
		else if (rcWaveforms.contains(e->pos()))
		{
			menu.addAction(m_mainS->actions()->viewZoomIn);
			menu.addAction(m_mainS->actions()->viewZoomOut);
			menu.addAction(m_mainS->actions()->viewZoomFull);
		}
		else
		{
		}
	}
	if (menu.actions().size() > 0)
	{
		QPoint ptGlobal = mapToGlobal(e->pos());
		QAction* act = menu.exec(ptGlobal);
		if (act == NULL)
			;
		else if (act == actAddPeakEndPoint)
		{
			addEadPeakXYEndPoint(vwi, info.iChosenPeak);
		}
		else if (act == actAddPeakMarker)
		{
			if (info.didxPossiblePeak >= 0)
				vwi->choosePeakAtDidx(info.didxPossiblePeak);
			else
				addMarker(vwi, ptPixmap.x());
		}
		else if (act == actAddTimeMarker)
		{
			addMarker(vwi, MarkerType_Time, ptPixmap.x());
		}
		else if (act == actRemoveMarker)
		{
			if (info.iChosenPeak >= 0)
				vwi->unchoosePeakAtIndex(info.iChosenPeak);
		}
		else if (act == actSettings)
		{
			openWaveEditorDialog(vwi, ptGlobal);
		}
		else if (act == actDelete)
		{
			QMessageBox msgBox;
			msgBox.setIcon(QMessageBox::Warning);
			msgBox.setText(tr("Delete Wave"));
			msgBox.setInformativeText(tr("This operation cannot be undone.  Do you really want to delete the wave named \"%0\"?").arg(wave->sName));
			msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
			msgBox.setDefaultButton(QMessageBox::Cancel);
			int ret = msgBox.exec();
			switch (ret) {
			case QMessageBox::Yes:
				vwi->remove();
				break;
			default:
				break;
			}

		}
	}

	e->accept();
	updateStatus();
}
Example #19
0
void XDialog::showEvent(QShowEvent *event)
{
  if(!_private->_shown)
  {
    _private->_shown = true;

    QRect availableGeometry = QApplication::desktop()->availableGeometry();

    QSettings settings(QSettings::UserScope, "OpenMFG.com", "OpenMFG");
    QString objName = objectName();
    QPoint pos = settings.value(objName + "/geometry/pos").toPoint();
    QSize lsize = settings.value(objName + "/geometry/size").toSize();

    if(lsize.isValid() && settings.value(objName + "/geometry/rememberSize", true).toBool())
      resize(lsize);

    // do I want to do this for a dialog?
    //_windowList.append(w);
    QRect r(pos, size());
    if(!pos.isNull() && availableGeometry.contains(r) && settings.value(objName + "/geometry/rememberPos", true).toBool())
      move(pos);

    QStringList parts = objectName().split(" ");
    QStringList search_parts;
    QString oName;
    while(!parts.isEmpty())
    {
      search_parts.append(parts.takeFirst());
      oName = search_parts.join(" ");

      // load and run an QtScript that applies to this window
      qDebug() << "Looking for a script on window " << oName;
      q.prepare("SELECT script_source, script_order"
                "  FROM script"
                " WHERE((script_name=:script_name)"
                "   AND (script_enabled))"
                " ORDER BY script_order;");
      q.bindValue(":script_name", oName);
      q.exec();
      while(q.next())
      {
        QString script = q.value("script_source").toString();
        if(!_private->_engine)
        {
          _private->_engine = new QScriptEngine();
          omfgThis->loadScriptGlobals(_private->_engine);
          QScriptValue mywindow = _private->_engine->newQObject(this);
          _private->_engine->globalObject().setProperty("mywindow", mywindow);
        }
  
        QScriptValue result = _private->_engine->evaluate(script);
        if (_private->_engine->hasUncaughtException())
        {
          int line = _private->_engine->uncaughtExceptionLineNumber();
          qDebug() << "uncaught exception at line" << line << ":" << result.toString();
        }
      }
    }
  }
  QDialog::showEvent(event);
}
Example #20
0
bool KisNodeDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if ((event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonDblClick)
        && (index.flags() & Qt::ItemIsEnabled))
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);

        const QRect iconsRect_ = iconsRect(option, index).translated(option.rect.topLeft());

        if (iconsRect_.isValid() && iconsRect_.contains(mouseEvent->pos())) {
            // Avoid conflicts with context menu events
            if (!(mouseEvent->buttons() & Qt::LeftButton)) {
                return false;
            }

            const int iconWidth = option.decorationSize.width();
            int xPos = mouseEvent->pos().x() - iconsRect_.left();
            if (xPos % (iconWidth + d->margin) < iconWidth) { //it's on an icon, not a margin
                Model::PropertyList propertyList = index.data(Model::PropertiesRole).value<Model::PropertyList>();
                int clickedProperty = -1;
                // Discover which of all properties was clicked
                for (int i = 0; i < propertyList.count(); ++i) {
                    if (propertyList[i].isMutable) {
                        xPos -= iconWidth + d->margin;
                    }
                    ++clickedProperty;
                    if (xPos < 0) break;
                }
                // Using Ctrl+click to enter stasis
                if (mouseEvent->modifiers() == Qt::ControlModifier
                    && propertyList[clickedProperty].canHaveStasis) {
                    // STEP 0: Prepare to Enter or Leave control key stasis
                    quint16 numberOfLeaves = model->rowCount(index.parent());
                    QModelIndex eachItem;
                    // STEP 1: Go.
                    if (propertyList[clickedProperty].isInStasis == false) { // Enter
                        /* Make every leaf of this node go State = False, saving the old property value to stateInStasis */
                        for (quint16 i = 0; i < numberOfLeaves; ++i) { // Foreach leaf in the node (index.parent())
                            eachItem = model->index(i, 0, index.parent());
                            // The entire property list has to be altered because model->setData cannot set individual properties
                            Model::PropertyList eachPropertyList = eachItem.data(Model::PropertiesRole).value<Model::PropertyList>();
                            eachPropertyList[clickedProperty].stateInStasis = eachPropertyList[clickedProperty].state.toBool();
                            eachPropertyList[clickedProperty].state = false;
                            eachPropertyList[clickedProperty].isInStasis = true;
                            model->setData(eachItem, QVariant::fromValue(eachPropertyList), Model::PropertiesRole);
                        }
                        /* Now set the current node's clickedProperty back to True, to save the user time
                        (obviously, if the user is clicking one item with ctrl+click, that item should
                        have a True property, value while the others are in stasis and set to False) */
                        // First refresh propertyList, otherwise old data will be saved back causing bugs
                        propertyList = index.data(Model::PropertiesRole).value<Model::PropertyList>();
                        propertyList[clickedProperty].state = true;
                        model->setData(index, QVariant::fromValue(propertyList), Model::PropertiesRole);
                    } else { // Leave
                        /* Make every leaf of this node go State = stateInStasis */
                        for (quint16 i = 0; i < numberOfLeaves; ++i) {
                            eachItem = model->index(i, 0, index.parent());
                            // The entire property list has to be altered because model->setData cannot set individual properties
                            Model::PropertyList eachPropertyList = eachItem.data(Model::PropertiesRole).value<Model::PropertyList>();
                            eachPropertyList[clickedProperty].state = eachPropertyList[clickedProperty].stateInStasis;
                            eachPropertyList[clickedProperty].isInStasis = false;
                            model->setData(eachItem, QVariant::fromValue(eachPropertyList), Model::PropertiesRole);
                        }
                    }
                } else {
                    propertyList[clickedProperty].state = !propertyList[clickedProperty].state.toBool();
                    model->setData(index, QVariant::fromValue(propertyList), Model::PropertiesRole);
                }
            }
            return true;
        }

        if (mouseEvent->button() == Qt::LeftButton &&
            mouseEvent->modifiers() == Qt::AltModifier) {

            d->view->setCurrentIndex(index);
            model->setData(index, true, Model::AlternateActiveRole);
            return true;
        }

        if (mouseEvent->button() != Qt::LeftButton) {
            d->view->setCurrentIndex(index);
            return false;
        }
    }
    else if (event->type() == QEvent::ToolTip) {
        if (!KisConfig().hidePopups()) {
            QHelpEvent *helpEvent = static_cast<QHelpEvent*>(event);
            d->tip.showTip(d->view, helpEvent->pos(), option, index);
        }
        return true;
    } else if (event->type() == QEvent::Leave) {
        d->tip.hide();
    }

    return false;
}
Example #21
0
void ChartWidget::mousePressEvent(QMouseEvent* e)
{
    //qDebug() << "mousePressEvent";
	QRect rcWaveforms = m_rcPixmap;

	ChartPointInfo info;
	QPoint ptPixmap = e->pos() - m_rcPixmap.topLeft();
	m_pixmap->fillChartPointInfo(ptPixmap, &info);
	m_clickInfo = info;
	ViewWaveInfo* vwi = info.vwi;

	m_ptMouseWidget = e->pos();
	m_ptMousePixmap = ptPixmap;
	m_ptClickWidget = m_ptMouseWidget;
	m_ptClickPixmap = m_ptMousePixmap;
	m_nClickSampleOffset = m_chartS->sampleOffset();
	
	const WaveInfo* wave = NULL;
	if (vwi != NULL)
		wave = vwi->wave();

	if (e->button() == Qt::LeftButton)
	{
		// If the user Ctrl+clicks on the selected FID wave while in peak editing mode:
		if (e->modifiers() == Qt::ControlModifier)
		{
			// If the user Ctrl+clicks on the selected FID wave while in peak editing mode:
			if (wave != NULL && m_chartS->params().peakMode == EadMarkerMode_Edit) {
				if (info.iChosenPeak < 0)
					addMarker(vwi, m_ptClickPixmap.x());
				else if (wave->peaksChosen[info.iChosenPeak].type == MarkerType_EadPeakXY) {
					addEadPeakXYEndPoint(vwi, info.iChosenPeak);
				}
			}
		}
		else {
			bool bIgnore = false;

			// Force no dragging of markers unless in edit mode:
			if (m_chartS->params().peakMode != EadMarkerMode_Edit) {
				if (m_clickInfo.iChosenPeak >= 0)
					bIgnore = true;
			}

			if (bIgnore)
			{
				;
			}
			// Clicked on a chosen peak:
			else if (info.iChosenPeak >= 0)
			{
				m_bDragging = true;
				setCursor(Qt::SizeHorCursor);
			}
			// Clicked on a detected peak:
			else if (info.didxPossiblePeak >= 0)
			{
				vwi->choosePeakAtDidx(info.didxPossiblePeak);
			}
			// Clicked on a wave:
			else if (wave != NULL)
			{
				m_bDragging = true;
				// REFACTOR: remove m_waveDrag and use m_clickInfo instead
				//m_waveDrag = vwi->waveInfo();
				m_nDragOrigDivisionOffset = vwi->divisionOffset();
				setCursor(Qt::SizeVerCursor);
			}
			else if (rcWaveforms.contains(e->pos()))
			{
				m_bDragging = true;
				m_bSelecting = true;
				setCursor(Qt::IBeamCursor);
				updateStatus();
				update();
			}
			else
			{
				m_bDragging = false;
			}
		}
	}
	else if (e->button() == Qt::MidButton)
	{
		m_clickInfo.iChosenPeak = -1;
		m_clickInfo.iMarkerDidx = -1;
		m_clickInfo.vwi = NULL;
		m_bDragging = true;
		setCursor(Qt::SizeHorCursor);
	}

	updateStatus();
}
Example #22
0
void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
{
    static const QEvent::Type contextMenuTrigger =
        QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ContextMenuOnMouseRelease).toBool() ?
        QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
    if (qApp->d_func()->inPopupMode()) {
        QWidget *activePopupWidget = qApp->activePopupWidget();
        QPoint mapped = event->pos();
        if (activePopupWidget != m_widget)
            mapped = activePopupWidget->mapFromGlobal(event->globalPos());
        bool releaseAfter = false;
        QWidget *popupChild  = activePopupWidget->childAt(mapped);

        if (activePopupWidget != qt_popup_down) {
            qt_button_down = 0;
            qt_popup_down = 0;
        }

        switch (event->type()) {
        case QEvent::MouseButtonPress:
        case QEvent::MouseButtonDblClick:
            qt_button_down = popupChild;
            qt_popup_down = activePopupWidget;
            break;
        case QEvent::MouseButtonRelease:
            releaseAfter = true;
            break;
        default:
            break; // nothing for mouse move
        }

        int oldOpenPopupCount = openPopupCount;

        if (activePopupWidget->isEnabled()) {
            // deliver event
            qt_replay_popup_mouse_event = false;
            QWidget *receiver = activePopupWidget;
            QPoint widgetPos = mapped;
            if (qt_button_down)
                receiver = qt_button_down;
            else if (popupChild)
                receiver = popupChild;
            if (receiver != activePopupWidget)
                widgetPos = receiver->mapFromGlobal(event->globalPos());
            QWidget *alien = receiver;

#if !defined(Q_OS_OSX) && !defined(Q_OS_IOS) // Cocoa tracks popups
            const bool reallyUnderMouse = activePopupWidget->rect().contains(mapped);
            const bool underMouse = activePopupWidget->underMouse();
            if (activePopupWidget != m_widget || (!underMouse && qt_button_down)) {
                // If active popup menu is not the first-level popup menu then we must emulate enter/leave events,
                // because first-level popup menu grabs the mouse and enter/leave events are delivered only to it
                // by QPA. Make an exception for first-level popup menu when the mouse button is pressed on widget.
                if (underMouse != reallyUnderMouse) {
                    if (reallyUnderMouse) {
                        QApplicationPrivate::dispatchEnterLeave(receiver, Q_NULLPTR, event->screenPos());
                        qt_last_mouse_receiver = receiver;
                    } else {
                        QApplicationPrivate::dispatchEnterLeave(Q_NULLPTR, qt_last_mouse_receiver, event->screenPos());
                        qt_last_mouse_receiver = receiver;
                        receiver = activePopupWidget;
                    }
                }
            } else if (!reallyUnderMouse) {
                alien = Q_NULLPTR;
            }
#endif

            QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(),
                          event->button(), event->buttons(), event->modifiers(), event->source());
            e.setTimestamp(event->timestamp());
            QApplicationPrivate::sendMouseEvent(receiver, &e, alien, receiver->window(), &qt_button_down, qt_last_mouse_receiver);
            qt_last_mouse_receiver = receiver;
        } else {
            // close disabled popups when a mouse button is pressed or released
            switch (event->type()) {
            case QEvent::MouseButtonPress:
            case QEvent::MouseButtonDblClick:
            case QEvent::MouseButtonRelease:
                activePopupWidget->close();
                break;
            default:
                break;
            }
        }

        if (qApp->activePopupWidget() != activePopupWidget
            && qt_replay_popup_mouse_event
            && QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::ReplayMousePressOutsidePopup).toBool()) {
            if (m_widget->windowType() != Qt::Popup)
                qt_button_down = 0;
            if (event->type() == QEvent::MouseButtonPress) {
                // the popup disappeared, replay the mouse press event
                QWidget *w = QApplication::widgetAt(event->globalPos());
                if (w && !QApplicationPrivate::isBlockedByModal(w)) {
                    // activate window of the widget under mouse pointer
                    if (!w->isActiveWindow()) {
                        w->activateWindow();
                        w->raise();
                    }

                    QWindow *win = w->windowHandle();
                    if (!win)
                        win = w->nativeParentWidget()->windowHandle();
                    if (win) {
                        const QRect globalGeometry = win->isTopLevel()
                            ? win->geometry()
                            : QRect(win->mapToGlobal(QPoint(0, 0)), win->size());
                        if (globalGeometry.contains(event->globalPos())) {
                            // Use postEvent() to ensure the local QEventLoop terminates when called from QMenu::exec()
                            const QPoint localPos = win->mapFromGlobal(event->globalPos());
                            QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPos(),
                                                             event->button(), event->buttons(), event->modifiers(), event->source());
                            QCoreApplicationPrivate::setEventSpontaneous(e, true);
                            e->setTimestamp(event->timestamp());
                            QCoreApplication::postEvent(win, e);
                        }
                    }
                }
            }
            qt_replay_popup_mouse_event = false;
#ifndef QT_NO_CONTEXTMENU
        } else if (event->type() == contextMenuTrigger
                   && event->button() == Qt::RightButton
                   && (openPopupCount == oldOpenPopupCount)) {
            QWidget *popupEvent = activePopupWidget;
            if (qt_button_down)
                popupEvent = qt_button_down;
            else if(popupChild)
                popupEvent = popupChild;
            QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
            QApplication::sendSpontaneousEvent(popupEvent, &e);
#endif
        }

        if (releaseAfter) {
            qt_button_down = 0;
            qt_popup_down = 0;
        }
        return;
    }

    // modal event handling
    if (QApplicationPrivate::instance()->modalState() && !qt_try_modal(m_widget, event->type()))
        return;

    // which child should have it?
    QWidget *widget = m_widget->childAt(event->pos());
    QPoint mapped = event->pos();

    if (!widget)
        widget = m_widget;

    if (event->type() == QEvent::MouseButtonPress)
        qt_button_down = widget;

    QWidget *receiver = QApplicationPrivate::pickMouseReceiver(m_widget, event->windowPos().toPoint(), &mapped, event->type(), event->buttons(),
                                                               qt_button_down, widget);

    if (!receiver) {
        if (event->type() == QEvent::MouseButtonRelease)
            QApplicationPrivate::mouse_buttons &= ~event->button();
        return;
    }
    if ((event->type() != QEvent::MouseButtonPress)
        || !(event->flags().testFlag(Qt::MouseEventCreatedDoubleClick))) {

        // The preceding statement excludes MouseButtonPress events which caused
        // creation of a MouseButtonDblClick event. QTBUG-25831
        QMouseEvent translated(event->type(), mapped, event->windowPos(), event->screenPos(),
                               event->button(), event->buttons(), event->modifiers(), event->source());
        translated.setTimestamp(event->timestamp());
        QApplicationPrivate::sendMouseEvent(receiver, &translated, widget, m_widget,
                                            &qt_button_down, qt_last_mouse_receiver);
        event->setAccepted(translated.isAccepted());
    }
#ifndef QT_NO_CONTEXTMENU
    if (event->type() == contextMenuTrigger && event->button() == Qt::RightButton
        && m_widget->rect().contains(event->pos())) {
        QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
        QGuiApplication::sendSpontaneousEvent(receiver, &e);
    }
#endif
}
Example #23
0
void COverlayDistance::drawArrows(const QPolygon& line, const QRect& viewport, QPainter& p)
{
    QPointF arrow[4] =
    {
        QPointF( 20.0, 7.0),     //front
        QPointF( 0.0, 0.0),      //upper tail
        QPointF( 5.0, 7.0),      //mid tail
        QPointF( 0.0, 15.0)      //lower tail
    };

    QPoint  pt, pt1, ptt;

    // draw direction arrows
    bool    start = true;
    double  heading;

    //generate arrow pic
    QImage arrow_pic(21,16, QImage::Format_ARGB32);
    arrow_pic.fill( qRgba(0,0,0,0));
    QPainter t_paint(&arrow_pic);
    USE_ANTI_ALIASING(t_paint, true);
    t_paint.setPen(QPen(Qt::white, 2));
    t_paint.setBrush(p.brush());
    t_paint.drawPolygon(arrow, 4);
    t_paint.end();

    foreach(pt,line)
    {
        if(start)                // no arrow on  the first loop
        {
            start = false;
        }
        else
        {
            if(!viewport.contains(pt))
            {
                pt1 = pt;
                continue;
            }
            if((abs(pt.x() - pt1.x()) + abs(pt.y() - pt1.y())) < 7)
            {
                pt1 = pt;
                continue;
            }
            // keep distance
            if((abs(pt.x() - ptt.x()) + abs(pt.y() - ptt.y())) > 100)
            {
                if(0 != pt.x() - pt1.x() && (pt.y() - pt1.y()))
                {
                    heading = ( atan2((double)(pt.y() - pt1.y()), (double)(pt.x() - pt1.x())) * 180.) / M_PI;

                    p.save();
                    // draw arrow between bullets
                    p.translate((pt.x() + pt1.x())/2,(pt.y() + pt1.y())/2);
                    p.rotate(heading);
                    p.drawImage(-11, -7, arrow_pic);
                    p.restore();
                    //remember last point
                    ptt = pt;
                }
            }
        }
        pt1 = pt;
    }

}
Example #24
0
void QDragManager::move( const QPoint & globalPos )
{
    if ( qt_xdnd_source_sameanswer.contains( globalPos ) &&
	 qt_xdnd_source_sameanswer.isValid() &&
	 !qt_xdnd_source_sameanswer.isEmpty() ) { // ### probably unnecessary
	return;
    }

    if ( qt_xdnd_deco ) {
	qt_xdnd_deco->move(globalPos-qt_xdnd_source_object->pixmapHotSpot());
	qt_xdnd_deco->raise();
    }

    Window target = 0;
    int lx = 0, ly = 0;
    if ( !XTranslateCoordinates( qt_xdisplay(), qt_xrootwin(), qt_xrootwin(),
				 globalPos.x(), globalPos.y(),
				 &lx, &ly, &target) ) {
	// somehow got to a different screen?  ignore for now
	return;
    }

    if ( target == qt_xrootwin() ) {
	// Ok.
    } else if ( target ) {
	target = qt_x11_findClientWindow( target, qt_wm_state, TRUE );
	if ( qt_xdnd_deco && !target || target == qt_xdnd_deco->winId() ) {
	    target = findRealWindow(globalPos,qt_xrootwin(),6);
	}
    }

    if ( target == 0 )
	target = qt_xrootwin();

    QWidget * w = QWidget::find( (WId)target );

    int emask = NoEventMask;
    if ( w && w->isDesktop() && !w->acceptDrops() ) {
	emask = EnterWindowMask;
	w = 0;
    }

    if ( target != qt_xdnd_current_target ) {
	if ( qt_xdnd_current_target )
	    qt_xdnd_send_leave();

	Atom * type[3]={0,0,0};
	const char* fmt;
	int nfmt=0;
	for (nfmt=0; nfmt<3 && (fmt=object->format(nfmt)); nfmt++)
	    type[nfmt] = qt_xdnd_str_to_atom( fmt );
	XClientMessageEvent enter;
	enter.type = ClientMessage;
	enter.window = target;
	enter.format = 32;
	enter.message_type = qt_xdnd_enter;
	enter.data.l[0] = object->source()->winId();
	enter.data.l[1] = 1 << 24; // flags
	enter.data.l[2] = type[0] ? *type[0] : 0; // ###
	enter.data.l[3] = type[1] ? *type[1] : 0;
	enter.data.l[4] = type[2] ? *type[2] : 0;

	qt_xdnd_current_target = target;
	// provisionally set the rectangle to 5x5 pixels...
	qt_xdnd_source_sameanswer = QRect( globalPos.x() - 2,
					   globalPos.y() -2 , 5, 5 );

	if ( w ) {
	    qt_handle_xdnd_enter( w, (const XEvent *)&enter );
	} else {
	    XSendEvent( qt_xdisplay(), target, FALSE, emask,
			(XEvent*)&enter );
	}
    }

    XClientMessageEvent move;
    move.type = ClientMessage;
    move.window = target;
    move.format = 32;
    move.message_type = qt_xdnd_position;
    move.window = target;
    move.data.l[0] = object->source()->winId();
    move.data.l[1] = 0; // flags
    move.data.l[2] = (globalPos.x() << 16) + globalPos.y();
    move.data.l[3] = qt_x_clipboardtime;
    move.data.l[4] = qt_xdnd_action_copy;

    if ( w )
	qt_handle_xdnd_position( w, (const XEvent *)&move );
    else
	XSendEvent( qt_xdisplay(), target, FALSE, emask,
		    (XEvent*)&move );
}
Example #25
0
//-----------------------------------------------------------------------------
// Function: AddressDelegate::editorEvent()
//-----------------------------------------------------------------------------
bool AddressDelegate::editorEvent(QEvent* event, QAbstractItemModel* model,
                                  QStyleOptionViewItem const& option, QModelIndex const& index)
{
    Q_ASSERT(event);
    Q_ASSERT(model);

    // Always reset the ad-hoc group modify flag.
    if (event->type() == QEvent::MouseButtonRelease)
    {
        groupModify_ = false;
    }

    // Make sure that the item is checkable.
    Qt::ItemFlags flags = model->flags(index);

    if (!(flags & Qt::ItemIsEnabled) || index.column() != ADDRESS_COL_LOCKED)
    {
        return false;
    }

    // Make sure that we have a check state.
    QVariant value = index.data(Qt::UserRole);

    if (!value.isValid())
    {
        return false;
    }

    bool newState = value.toBool();

    // Handle the mouse button events.
    if (event->type() == QEvent::MouseButtonPress)
    {
        const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

        QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                              option.decorationSize,
                                              QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
                                                      option.rect.width() - (2 * textMargin),
                                                      option.rect.height()));

        if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
        {
            return false;
        }

        newState = !value.toBool();
        groupModify_ = true;
        groupState_ = newState;
    }
    else if (event->type() == QEvent::MouseMove)
    {
        if (!groupModify_ || value.toBool() == groupState_)
        {
            return false;
        }

        const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;

        QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                              option.decorationSize,
                                              QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
                                                      option.rect.width() - (2 * textMargin),
                                                      option.rect.height()));

        if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
        {
            return false;
        }

        newState = groupState_;
    }
    else if (event->type() == QEvent::KeyPress)
    {
        if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space &&
                static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
        {
            return false;
        }
    }
    else
    {
        return false;
    }

    return model->setData(index, newState, Qt::UserRole);
}
Example #26
0
/// XXX
void MiamStyle::drawScrollBar(QPainter *p, const QWidget *widget) const
{
    QStyleOptionSlider scrollbar;
    scrollbar.palette = QApplication::palette();

    const QScrollBar *sc = qobject_cast<const QScrollBar *>(widget);
    scrollbar.initFrom(sc);


    QRect subLineRect = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarSubLine, sc);
    QRect addLineRect = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarAddLine, sc);
    QRect sliderRect = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, &scrollbar, QStyle::SC_ScrollBarSlider, sc);

    //qDebug() << subLineRect << sliderRect << addLineRect;


    if (sc->orientation() == Qt::Vertical) {
        subLineRect.adjust(0, 0, -1, 0);
        addLineRect.adjust(0, 0, -1, 0);
        sliderRect.adjust(0, 0, -1, 0);
    } else {
        subLineRect.adjust(0, 0, 0, -1);
        addLineRect.adjust(0, 0, 0, -1);
        sliderRect.adjust(0, 0, 0, -1);
    }

    p->setPen(Qt::NoPen);
    p->setBrush(scrollbar.palette.window());
    p->drawRect(sc->rect());

    p->setBrush(scrollbar.palette.base().color().darker(125));
    p->drawRect(sliderRect);

    // Highlight
    p->save();
    QPoint pos = sc->mapFromGlobal(QCursor::pos());
    p->setPen(scrollbar.palette.highlight().color());

    if (!sc->isSliderDown()) {
        p->setBrush(scrollbar.palette.highlight().color().lighter());
        if (subLineRect.contains(pos)) {
            p->drawRect(subLineRect);
        } else if (sliderRect.contains(pos)) {
            p->drawRect(sliderRect);
        } else if (addLineRect.contains(pos)) {
            p->drawRect(addLineRect);
        }
    } else {
        p->setBrush(scrollbar.palette.highlight().color());
        //if (_isDown == 0) {
        //	p->drawRect(subLineRect);
        //} else if (_isDown == 1) {
        //	p->drawRect(sliderRect);
        //} else if (_isDown == 2) {
        //	p->drawRect(addLineRect);
        //}
    }
    p->restore();

    // Draw sort indicator
    static const QPointF upArrow[3] = {
        QPointF(0.0, 1.0),
        QPointF(1.0, 0.0),
        QPointF(2.0, 1.0)
    };
    static const QPointF downArrow[3] = {
        QPointF(0.0, 0.0),
        QPointF(2.0, 0.0),
        QPointF(1.0, 1.0)
    };
    static const QPointF leftArrow[3] = {
        QPointF(0.0, 1.0),
        QPointF(1.0, 0.0),
        QPointF(1.0, 2.0)
    };
    static const QPointF rightArrow[3] = {
        QPointF(0.0, 0.0),
        QPointF(1.0, 1.0),
        QPointF(0.0, 2.0)
    };

    // Arrows
    p->save();
    if (scrollbar.palette.windowText().color().value() < 128) {
        p->setPen(scrollbar.palette.dark().color());
        p->setBrush(scrollbar.palette.dark());
    } else {
        p->setPen(scrollbar.palette.mid().color());
        p->setBrush(scrollbar.palette.mid());
    }

    QTransform t;
    float ratio = (float) subLineRect.height() / 4.0;
    t.scale(ratio, ratio);

    if (sc->orientation() == Qt::Vertical) {
        QPolygonF up, down;
        up.append(t.map(upArrow[0]));
        up.append(t.map(upArrow[1]));
        up.append(t.map(upArrow[2]));
        down.append(t.map(downArrow[0]));
        down.append(t.map(downArrow[1]));
        down.append(t.map(downArrow[2]));
        p->translate(subLineRect.width() / 4.0, subLineRect.height() / 3.0);
        p->drawPolygon(up);
        p->translate(0, addLineRect.y());
        p->drawPolygon(down);
    } else {
        QPolygonF left, right;
        left.append(t.map(leftArrow[0]));
        left.append(t.map(leftArrow[1]));
        left.append(t.map(leftArrow[2]));
        right.append(t.map(rightArrow[0]));
        right.append(t.map(rightArrow[1]));
        right.append(t.map(rightArrow[2]));
        p->translate(subLineRect.height() / 3.0, subLineRect.width() / 4.0);
        p->drawPolygon(left);
        p->translate(addLineRect.x(), 0);
        p->drawPolygon(right);
    }
    p->restore();
}
void GradientPreview::mouseReleaseEvent(QMouseEvent *m)
{
	if (isEditable)
	{
		QRect fpo;
		if (m->button() == Qt::LeftButton)
		{
			if ((Mpressed) && (ActStop > 0) && (ActStop != static_cast<int>(StopM.count()-1)) && (outside || m->y() > 60))
			{
				onlyselect = false;
				fill_gradient.removeStop(ActStop);
				ActStop = 0;
				repaint();
				QList<VColorStop*> cstops = fill_gradient.colorStops();
				emit selectedStop(cstops.at(ActStop));
			}
			if ((m->y() < height()) && (m->y() > 43) && (m->x() > 0) && (m->x() < width()) && (ActStop == -1))
			{
				QList<VColorStop*> cstops = fill_gradient.colorStops();
				double  newStop = static_cast<double>((m->x() - 10)) / (static_cast<double>(width())-20);
				QColor  stopColor = (cstops.count() > 0) ? cstops.at(0)->color : QColor(255, 255, 255);
				QString stopName  = (cstops.count() > 0) ? cstops.at(0)->name  : QString("White");
				int     stopShade = (cstops.count() > 0) ? cstops.at(0)->shade : 100;
				fill_gradient.addStop(stopColor, newStop, 0.5, 1.0, stopName, stopShade);
				repaint();
				onlyselect = false;
				cstops = fill_gradient.colorStops();
				for (int yg = 0; yg < static_cast<int>(StopM.count()); ++yg)
				{
					fpo = QRect(static_cast<int>(StopM[yg])-4, 43, 8, 13);
					if (fpo.contains(m->pos()))
					{
						ActStop = yg;
						emit selectedStop(cstops.at(ActStop));
						repaint();
						break;
					}
				}
			}
		}
		else if (m->button() == Qt::RightButton)
		{
			Mpressed = false;
			QList<VColorStop*> cstops = fill_gradient.colorStops();
			int stop = -1;
			for (int yg = 0; yg < static_cast<int>(StopM.count()); ++yg)
			{
				fpo = QRect(static_cast<int>(StopM[yg])-4, 43, 8, 13);
				if (fpo.contains(m->pos()))
				{
					stop = yg;
					break;
				}
			}
			contextStop = stop;
			mPos = m->pos();
			QMenu *pmen = new QMenu();
			qApp->changeOverrideCursor(QCursor(Qt::ArrowCursor));
			pmen->addAction( tr("Add Stop"), this, SLOT(addStop()));
			if (stop != -1)
				pmen->addAction( tr("Remove Stop"), this, SLOT(removeStop()));
			pmen->exec(QCursor::pos());
			delete pmen;
		}
	}
	Mpressed = false;
	if (!onlyselect)
		emit gradientChanged();
}
Example #28
-1
UBRubberBand::enm_resizingMode UBRubberBand::determineResizingMode(QPoint pos)
{
    if (mMouseIsPressed)
        return mResizingMode;
    
    QRect resizerTop    (mResizingBorderHeight               , 0                             , rect().width()-2*mResizingBorderHeight, mResizingBorderHeight                    );
    QRect resizerBottom (mResizingBorderHeight               , rect().height() - mResizingBorderHeight, rect().width()-2*mResizingBorderHeight, mResizingBorderHeight                    );
    QRect resizerLeft   (0                          , mResizingBorderHeight                  , mResizingBorderHeight                 , rect().height() - 2*mResizingBorderHeight);
    QRect resizerRight  (rect().width()-mResizingBorderHeight, mResizingBorderHeight                  , mResizingBorderHeight                 , rect().height() - 2*mResizingBorderHeight);

    QRect resizerTopLeft    (0                          , 0                             , mResizingBorderHeight, mResizingBorderHeight);
    QRect resizerTopRight   (rect().width()-mResizingBorderHeight, 0                             , mResizingBorderHeight, mResizingBorderHeight);
    QRect resizerBottomLeft (0                          , rect().height() - mResizingBorderHeight, mResizingBorderHeight, mResizingBorderHeight);
    QRect resizerBottomRight(rect().width()-mResizingBorderHeight, rect().height() - mResizingBorderHeight, mResizingBorderHeight, mResizingBorderHeight);

    enm_resizingMode resizingMode;
    
    QTransform cursorTransrofm;

    if (resizerTop.contains(pos))
    {
        resizingMode = Top;
        cursorTransrofm.rotate(90);
    }
    else
    if (resizerBottom.contains(pos))
    {
        resizingMode = Bottom;
        cursorTransrofm.rotate(90);
    }
    else
    if (resizerLeft.contains(pos))
    {
        resizingMode = Left;
    }
    else
    if (resizerRight.contains(pos))
    {
        resizingMode = Right;
    }
    else
    if (resizerTopLeft.contains(pos))
    {
        resizingMode = TopLeft;
        cursorTransrofm.rotate(45);
    }
    else
    if (resizerTopRight.contains(pos))
    {
        resizingMode = TopRight;
        cursorTransrofm.rotate(-45);
    }
    else
    if (resizerBottomLeft.contains(pos))
    {
        resizingMode = BottomLeft;
        cursorTransrofm.rotate(-45);
    }
    else
    if (resizerBottomRight.contains(pos))
    {
        resizingMode = BottomRight;
        cursorTransrofm.rotate(45);
    }
    else
        resizingMode = None;
    
    if (None != resizingMode)
    {
        QPixmap pix(":/images/cursors/resize.png");
        QCursor resizeCursor  = QCursor(pix.transformed(cursorTransrofm, Qt::SmoothTransformation), pix.width() / 2,  pix.height() / 2);
        setCursor(resizeCursor);
    }
    else
        unsetCursor();

    return resizingMode;
}