Пример #1
0
void UBGraphicsRuler::DrawLine(const QPointF& scenePos, qreal width)
{
    QPointF itemPos = mapFromScene(scenePos);

    qreal y;
    if (drawLineDirection == 0)
    {
        y = rect().y() + rect().height() + width / 2;
    }
    else
    {
        y = rect().y() - width /2;
    }
    if (itemPos.x() < rect().x() + sLeftEdgeMargin)
        itemPos.setX(rect().x() + sLeftEdgeMargin);
    if (itemPos.x() > rect().x() + rect().width() - sLeftEdgeMargin)
        itemPos.setX(rect().x() + rect().width() - sLeftEdgeMargin);

    itemPos.setY(y);
    itemPos = mapToScene(itemPos);

    // We have to use "pointed" line for marker tool
    scene()->drawLineTo(itemPos, width, UBDrawingController::drawingController()->stylusTool() != UBStylusTool::Marker);
}
Пример #2
0
QPointF SCgNode::cross(const QPointF &from, float dot) const
{
    QPointF p(0.f, 0.f);

    if (!mIsContentVisible)
    {
        QVector2D vec(from - scenePos());
        p = vec.normalized().toPointF() * (mSize.width() / 2.f);
    }else
    {

        // count intersection with content border
        QPolygonF polygon(boundingRect());
        QPointF p1 = polygon.last();
        QPointF p2, intersectPoint;
        QLineF line, pair(p, mapFromScene(from));
        bool haveItersect = false;

        for (int i = 0; i < polygon.size(); i++)
        {
            p2 = polygon.at(i);
            line = QLineF(p1, p2);
            QLineF::IntersectType intersectType = line.intersect(pair, &intersectPoint);
            if (intersectType == QLineF::BoundedIntersection)
            {
                haveItersect = true;
                break;
            }

            p1 = p2;
        }
        p = haveItersect ? intersectPoint : p;
    }

    return mapToScene(p);
}
Пример #3
0
void QgsLayoutView::mousePressEvent( QMouseEvent *event )
{
  if ( mTool )
  {
    std::unique_ptr<QgsLayoutViewMouseEvent> me( new QgsLayoutViewMouseEvent( this, event ) );
    mTool->layoutPressEvent( me.get() );
    event->setAccepted( me->isAccepted() );
  }

  if ( !mTool || !event->isAccepted() )
  {
    if ( event->button() == Qt::MidButton )
    {
      // Pan layout with middle mouse button
      setTool( mMidMouseButtonPanTool );
      event->accept();
    }
    else if ( event->button() == Qt::RightButton && mMenuProvider )
    {
      QMenu *menu = mMenuProvider->createContextMenu( this, currentLayout(), mapToScene( event->pos() ) );
      if ( menu )
      {
        menu->exec( event->globalPos() );
        delete menu;
      }
    }
    else
    {
      QGraphicsView::mousePressEvent( event );
    }
  }
  else
  {
    QGraphicsView::mousePressEvent( event );
  }
}
Пример #4
0
void GameMapViewer::wheelEvent(QWheelEvent* event)
{
    
    const QPointF pscene = mapToScene(event->pos());

    int delta = event->delta();
    qreal factor = std::pow(1.00052, delta);
    qDebug() << _zoom;

    int zoomBlock = _zoom + event->delta();
    if (zoomBlock > 400 || zoomBlock < -200)
    {
        return;
    }

    _zoom += delta;
    
    scale(factor, factor);

    const QPointF p1mouse = mapFromScene(pscene);
    const QPointF move = p1mouse - event->pos();
    horizontalScrollBar()->setValue(move.x() + horizontalScrollBar()->value());
    verticalScrollBar()->setValue(move.y() + verticalScrollBar()->value());
}
Пример #5
0
void CityLordView::mouseMoveEvent(QMouseEvent * e){
    int move;
    QPointF currentPos = mapToScene(e->pos());
    if(startMouse.x() < currentPos.x() and currentPos.x()>-1520){   // -rows*baselength
        move = currentPos.x()-startMouse.x();
        px-= move;
        lastPos.setX(lastPos.x()-move);
    }else if(startMouse.x() > currentPos.x() and currentPos.x()<1520){  // rows*baselength
        move = startMouse.x()-currentPos.x();
        px+= move;
        lastPos.setX(lastPos.x()+move);
    }
    if(startMouse.y() < currentPos.y() and currentPos.y()>0){   // 0
        move = currentPos.y()-startMouse.y();
        py-=move;
        lastPos.setY(lastPos.y()-move);
    }else if(startMouse.y() > currentPos.y() and currentPos.y()<1500){// columns*baseheight
        move = startMouse.y()-currentPos.y();
        py+=move;
        lastPos.setY(lastPos.y()+move);
    }
    lastPos = currentPos;
    setSceneRect(-((WIDTH/2)-(BASE.width()/2))+px, py, WIDTH-2, HEIGHT-2);
}
void CodeViewInteractiveRect::updateIntRectPos( QGraphicsSceneMouseEvent * event)
{
	// calculate position

	QPointF oldpos = this->pos();
	QPointF newpos(oldpos);
	newpos.setY(newpos.y()+(event->pos().y()-event->lastPos().y()));
	this->setPos(newpos);

	if (this->scenePos().y() - rect_height/2 < -m_codeminimap->sceneRect().height()/2)
	{
		// item moved over top border -> limit movement
		if ((event->pos().y()-event->lastPos().y()) < 0)
		{
			qreal corrected_position = -m_codeminimap->sceneRect().height()/2 + rect_height/2;
			newpos.setY(corrected_position);
			this->setPos(newpos);
		}
	}
	else if (this->scenePos().y() + rect_height/2 > m_codeminimap->sceneRect().height()/2)
	{
		// item moved over bottom border -> limit movement
		if ((event->pos().y()-event->lastPos().y()) > 0)
		{
			qreal corrected_position = m_codeminimap->sceneRect().height()/2 - rect_height/2;
			newpos.setY(corrected_position);
			this->setPos(newpos);
		}
	}

	

	// TODO: scroll up or down to show next text content

	// calculate corresponding scroll bar position for code view
	qreal total_dist = m_codeminimap->sceneRect().height()-rect_height;
	qreal val = (scenePos().y() + (total_dist/2)) / total_dist;
	m_codeminimap->mCodeView->setScrollBarValue(val);

#if 0

	qreal y = this->pos().y() - rect_height / 2;
	// check if rect is fully visible
	qreal calc_rect_height = mapToScene(QPointF(0,rect_height)).y() - this->mapToScene(QPointF(0,0)).y();
	// check if rect is too high
	qreal top_y = m_codeminimap->mapToScene(QPoint(0,0)).y();
	qreal bottom_y = m_codeminimap->mapToScene(QPoint(0,m_codeminimap->height())).y();
	if ((top_y - y) > 0.0)	// rect is too high
	{
		// correct position
		qreal corrected_position = top_y + rect_height/2;
		newpos.setY(corrected_position);
		this->setPos(newpos);

		// update content
		m_codeminimap->update(m_codeminimap->rect());
		this->update(this->boundingRect());

		return;

		// TODO: limit movement !!!

		// can we scroll up?
		/*
		if (m_codeminimap->mCodeView->verticalScrollBar()->maximum() > m_codeminimap->mCodeView->verticalScrollBar()->minimum())
		{
			qreal correctedvalue = qreal(m_codeminimap->mCodeView->verticalScrollBar()->value())-qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum());
			qreal interval = qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum()) - qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum());
			qreal val =  correctedvalue / interval;
			if (val < 0.0)
				val = -val;
			qDebug() << " calculated value " << val;
			val = val - 0.001;
			if (val < 0.0) val = 0.0;
			qDebug() << " set scroll value to " << val;
			m_codeminimap->mCodeView->setScrollBarValue(val);
			return;
		}
		else if (m_codeminimap->mCodeView->verticalScrollBar()->minimum() > m_codeminimap->mCodeView->verticalScrollBar()->maximum())
		{
			qreal correctedvalue = qreal(m_codeminimap->mCodeView->verticalScrollBar()->value())-qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum());
			qreal interval = qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum()) - qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum());
			qreal val =  correctedvalue / interval;
			if (val < 0.0)
				val = -val;
			qDebug() << " calculated value " << val;
			val -= 0.001;
			if (val < 0.0) val = 0.0;
			qDebug() << " set scroll value to " << val;
			m_codeminimap->mCodeView->setScrollBarValue(val);
			return;
		}
		*/
	}

	// check if rect is too low
	if (((y+rect_height) - bottom_y) > 0.0)
	{
		qDebug() << "rect too low!!!";

		qreal corrected_position = bottom_y - rect_height/2;
		newpos.setY(corrected_position);
		this->setPos(newpos);

		// TODO: limit movement !!!

		/*
		// can we scroll down?
		if (m_codeminimap->mCodeView->verticalScrollBar()->maximum() > m_codeminimap->mCodeView->verticalScrollBar()->minimum())
		{
			qreal correctedvalue = qreal(m_codeminimap->mCodeView->verticalScrollBar()->value())-qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum());
			qreal interval = qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum()) - qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum());
			qreal val =  correctedvalue / interval;
			if (val < 0.0)
				val = -val;
			qDebug() << " calculated value " << val;
			val += 0.001;
			if (val > 1.0) val = 1.0;
			qDebug() << " set scroll value to " << val;
			m_codeminimap->mCodeView->setScrollBarValue(val);
			return;
		}
		else if (m_codeminimap->mCodeView->verticalScrollBar()->minimum() > m_codeminimap->mCodeView->verticalScrollBar()->maximum())
		{
			qreal correctedvalue = qreal(m_codeminimap->mCodeView->verticalScrollBar()->value())-qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum());
			qreal interval = qreal(m_codeminimap->mCodeView->verticalScrollBar()->minimum()) - qreal(m_codeminimap->mCodeView->verticalScrollBar()->maximum());
			qreal val =  correctedvalue / interval;
			if (val < 0.0)
				val = -val;
			qDebug() << " calculated value " << val;
			val += 0.001;
			if (val > 1.0) val = 1.0;
			qDebug() << " set scroll value to " << val;
			m_codeminimap->mCodeView->setScrollBarValue(val);
			return;
		}
		*/
	}
	
	
	qreal val = (pos().y()-(rect_height/2) + (m_codeminimap->sceneRect().height()/2)) / m_codeminimap->sceneRect().height();

	qDebug() << "value = " << val;
	m_codeminimap->mCodeView->setScrollBarValue(val);

#endif

	// with new position update code view
	m_codeminimap->update(m_codeminimap->rect());
	this->update(this->boundingRect());
}
Пример #7
0
void QgsComposerView::mouseReleaseEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPoint mousePressStopPoint = e->pos();
  int diffX = mousePressStopPoint.x() - mMousePressStartPos.x();
  int diffY = mousePressStopPoint.y() - mMousePressStartPos.y();

  //was this just a click? or a click and drag?
  bool clickOnly = false;
  if ( qAbs( diffX ) < 2 && qAbs( diffY ) < 2 )
  {
    clickOnly = true;
  }

  QPointF scenePoint = mapToScene( e->pos() );

  if ( mPanning )
  {
    mPanning = false;

    if ( clickOnly && e->button() == Qt::MidButton )
    {
      //middle mouse button click = recenter on point

      //get current visible part of scene
      QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
      QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );
      visibleRect.scale( 1, scenePoint.x(), scenePoint.y() );
      QRectF boundsRect = visibleRect.toRectF();

      //zoom view to fit desired bounds
      fitInView( boundsRect, Qt::KeepAspectRatio );
    }

    //set new cursor
    if ( mCurrentTool == Pan )
    {
      viewport()->setCursor( Qt::OpenHandCursor );
    }
    else
    {
      if ( composition() )
      {
        //allow composer items to change cursor
        composition()->setPreventCursorChange( false );
      }
      viewport()->setCursor( Qt::ArrowCursor );
    }
  }

  if ( mMarqueeSelect )
  {
    endMarqueeSelect( e );
    return;
  }

  switch ( mCurrentTool )
  {
    case Select:
    {
      QGraphicsView::mouseReleaseEvent( e );
      break;
    }

    case Zoom:
    {
      if ( mMarqueeZoom )
      {
        endMarqueeZoom( e );
      }
      break;
    }

    case MoveItemContent:
    {
      if ( mMoveContentItem )
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( 0, 0 );
        }

        double moveX = scenePoint.x() - mMoveContentStartPos.x();
        double moveY = scenePoint.y() - mMoveContentStartPos.y();

        composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) );
        mMoveContentItem->moveContent( -moveX, -moveY );
        composition()->endCommand();
        mMoveContentItem = 0;
      }
      break;
    }
    case AddArrow:
      if ( composition() )
      {
        QPointF scenePoint = mapToScene( e->pos() );
        QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
        QgsComposerArrow* composerArrow = new QgsComposerArrow( mRubberBandStartPos, QPointF( snappedScenePoint.x(), snappedScenePoint.y() ), composition() );
        composition()->addComposerArrow( composerArrow );

        composition()->clearSelection();
        composerArrow->setSelected( true );
        emit selectedItemChanged( composerArrow );

        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) );
      }
      break;

    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
      addShape( mCurrentTool );
      break;

    case AddMap:
      if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      if ( composition() )
      {
        QgsComposerMap* composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
        composition()->addComposerMap( composerMap );

        composition()->clearSelection();
        composerMap->setSelected( true );
        emit selectedItemChanged( composerMap );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) );
      }
      break;

    case AddHtml:
      if ( composition() )
      {
        QgsComposerHtml* composerHtml = new QgsComposerHtml( composition(), true );
        QgsAddRemoveMultiFrameCommand* command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added,
            composerHtml, composition(), tr( "Html item added" ) );
        composition()->undoStack()->push( command );
        QgsComposerFrame* frame = new QgsComposerFrame( composition(), composerHtml, mRubberBandItem->transform().dx(),
            mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(),
            mRubberBandItem->rect().height() );
        composition()->beginMultiFrameCommand( composerHtml, tr( "Html frame added" ) );
        composerHtml->addFrame( frame );
        composition()->endMultiFrameCommand();

        composition()->clearSelection();
        frame->setSelected( true );
        emit selectedItemChanged( frame );

        removeRubberBand();
        emit actionFinished();
      }
    default:
      break;
  }
}
Пример #8
0
void QgsComposerView::mousePressEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPointF scenePoint = mapToScene( e->pos() );
  QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
  mMousePressStartPos = e->pos();

  //lock/unlock position of item with right click
  if ( e->button() == Qt::RightButton )
  {
    QgsComposerItem* selectedItem = composition()->composerItemAt( scenePoint );
    if ( selectedItem )
    {
      bool lock = selectedItem->positionLock() ? false : true;
      selectedItem->setPositionLock( lock );
      selectedItem->update();
    }
    return;
  }
  else if ( e->button() == Qt::MidButton )
  {
    //pan composer with middle button
    mPanning = true;
    mMouseLastXY = e->pos();
    if ( composition() )
    {
      //lock cursor to closed hand cursor
      composition()->setPreventCursorChange( true );
    }
    viewport()->setCursor( Qt::ClosedHandCursor );
    return;
  }

  switch ( mCurrentTool )
  {
      //select/deselect items and pass mouse event further
    case Select:
    {
      //check if we are clicking on a selection handle
      if ( composition()->selectionHandles()->isVisible() )
      {
        //selection handles are being shown, get mouse action for current cursor position
        QgsComposerMouseHandles::MouseAction mouseAction = composition()->selectionHandles()->mouseActionForScenePos( scenePoint );

        if ( mouseAction != QgsComposerMouseHandles::MoveItem && mouseAction != QgsComposerMouseHandles::NoAction && mouseAction != QgsComposerMouseHandles::SelectItem )
        {
          //mouse is over a resize handle, so propagate event onward
          QGraphicsView::mousePressEvent( e );
          return;
        }
      }

      QgsComposerItem* selectedItem = 0;
      QgsComposerItem* previousSelectedItem = 0;

      if ( e->modifiers() & Qt::ControlModifier )
      {
        //CTRL modifier, so we are trying to select the next item below the current one
        //first, find currently selected item
        QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems();
        if ( selectedItems.size() > 0 )
        {
          previousSelectedItem = selectedItems.at( 0 );
        }
      }

      if ( previousSelectedItem )
      {
        //select highest item just below previously selected item at position of event
        selectedItem = composition()->composerItemAt( scenePoint, previousSelectedItem );

        //if we didn't find a lower item we'll use the top-most as fall-back
        //this duplicates mapinfo/illustrator/etc behaviour where ctrl-clicks are "cyclic"
        if ( !selectedItem )
        {
          selectedItem = composition()->composerItemAt( scenePoint );
        }
      }
      else
      {
        //select topmost item at position of event
        selectedItem = composition()->composerItemAt( scenePoint );
      }

      if ( !selectedItem )
      {
        //not clicking over an item, so start marquee selection
        startMarqueeSelect( scenePoint );
        break;
      }

      if (( !selectedItem->selected() ) &&        //keep selection if an already selected item pressed
          !( e->modifiers() & Qt::ShiftModifier ) ) //keep selection if shift key pressed
      {
        composition()->clearSelection();
      }

      if (( e->modifiers() & Qt::ShiftModifier ) && ( selectedItem->selected() ) )
      {
        //SHIFT-clicking a selected item deselects it
        selectedItem->setSelected( false );

        //Check if we have any remaining selected items, and if so, update the item panel
        QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems();
        if ( selectedItems.size() > 0 )
        {
          emit selectedItemChanged( selectedItems.at( 0 ) );
        }
      }
      else
      {
        selectedItem->setSelected( true );
        QGraphicsView::mousePressEvent( e );
        emit selectedItemChanged( selectedItem );
      }
      break;
    }

    case Zoom:
    {
      if ( !( e->modifiers() & Qt::ShiftModifier ) )
      {
        //zoom in action
        startMarqueeZoom( scenePoint );
      }
      else
      {
        //zoom out action, so zoom out and recenter on clicked point
        double scaleFactor = 2;
        //get current visible part of scene
        QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
        QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

        //transform the mouse pos to scene coordinates
        QPointF scenePoint = mapToScene( e->pos() );

        visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() );
        QRectF boundsRect = visibleRect.toRectF();

        //zoom view to fit desired bounds
        fitInView( boundsRect, Qt::KeepAspectRatio );
      }
      break;
    }

    case Pan:
    {
      //pan action
      mPanning = true;
      mMouseLastXY = e->pos();
      viewport()->setCursor( Qt::ClosedHandCursor );
      break;
    }

    case MoveItemContent:
    {
      //get a list of items at clicked position
      QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos() );
      if ( itemsAtCursorPos.size() == 0 )
      {
        //no items at clicked position
        return;
      }

      //find highest QgsComposerItem at clicked position
      //(other graphics items may be higher, eg selection handles)
      QList<QGraphicsItem*>::iterator itemIter = itemsAtCursorPos.begin();
      for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter )
      {
        QgsComposerItem* item = dynamic_cast<QgsComposerItem *>(( *itemIter ) );
        if ( item )
        {
          //we've found the highest QgsComposerItem
          mMoveContentStartPos = scenePoint;
          mMoveContentItem = item;
          break;
        }
      }

      //no QgsComposerItem at clicked position
      return;
    }

    case AddArrow:
    {
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem = new QGraphicsLineItem( snappedScenePoint.x(), snappedScenePoint.y(), snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem->setZValue( 1000 );
      scene()->addItem( mRubberBandLineItem );
      scene()->update();
      break;
    }

    //create rubber band for map and ellipse items
    case AddMap:
    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
    case AddHtml:
    {
      QTransform t;
      mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 );
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      t.translate( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandItem->setTransform( t );
      mRubberBandItem->setZValue( 1000 );
      scene()->addItem( mRubberBandItem );
      scene()->update();
    }
    break;

    case AddLabel:
      if ( composition() )
      {
        QgsComposerLabel* newLabelItem = new QgsComposerLabel( composition() );
        newLabelItem->setText( tr( "QGIS" ) );
        newLabelItem->adjustSizeToText();
        newLabelItem->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLabelItem->rect().width(), newLabelItem->rect().height() ) );
        composition()->addComposerLabel( newLabelItem );

        composition()->clearSelection();
        newLabelItem->setSelected( true );
        emit selectedItemChanged( newLabelItem );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) );
      }
      break;

    case AddScalebar:
      if ( composition() )
      {
        QgsComposerScaleBar* newScaleBar = new QgsComposerScaleBar( composition() );
        newScaleBar->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 20, 20 ) );
        composition()->addComposerScaleBar( newScaleBar );
        QList<const QgsComposerMap*> mapItemList = composition()->composerMapItems();
        if ( mapItemList.size() > 0 )
        {
          newScaleBar->setComposerMap( mapItemList.at( 0 ) );
        }
        newScaleBar->applyDefaultSize(); //4 segments, 1/5 of composer map width

        composition()->clearSelection();
        newScaleBar->setSelected( true );
        emit selectedItemChanged( newScaleBar );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) );
      }
      break;

    case AddLegend:
    {
      if ( composition() )
      {
        QgsComposerLegend* newLegend = new QgsComposerLegend( composition() );
        newLegend->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLegend->rect().width(), newLegend->rect().height() ) );
        composition()->addComposerLegend( newLegend );
        newLegend->updateLegend();

        composition()->clearSelection();
        newLegend->setSelected( true );
        emit selectedItemChanged( newLegend );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) );
      }
      break;
    }
    case AddPicture:
      if ( composition() )
      {
        QgsComposerPicture* newPicture = new QgsComposerPicture( composition() );
        newPicture->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 30, 30 ) );
        composition()->addComposerPicture( newPicture );

        composition()->clearSelection();
        newPicture->setSelected( true );
        emit selectedItemChanged( newPicture );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) );
      }
      break;
    case AddTable:
      if ( composition() )
      {
        QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( composition() );
        newTable->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 50, 50 ) );
        composition()->addComposerTable( newTable );

        composition()->clearSelection();
        newTable->setSelected( true );
        emit selectedItemChanged( newTable );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newTable, tr( "Table added" ) );
      }
      break;
    default:
      break;
  }
}
Пример #9
0
void SCgView::contextMenuEvent(QContextMenuEvent *event)
{
    if (event->reason() == QContextMenuEvent::Keyboard || event->reason() == QContextMenuEvent::Other)
        return;
    // get scg-object under mouse
    QPointF mousePos = mapToScene(event->pos());/* +
                                QPointF(horizontalScrollBar()->value(), verticalScrollBar()->value()) -
                                scene()->sceneRect().topLeft();*/

    SCgObject *object = static_cast<SCgScene*>(scene())->objectAt(mousePos);

    // create context menu
    if (mContextMenu)
    {
        delete mContextMenu;
        mContextMenu = 0;
    }

    // selection by right mouse click
    if(object && !object->isSelected())
    {
        scene()->clearSelection();
        object->setSelected(true);
    }

    // create new context menu
    mContextMenu = new QMenu;

    if (mContextObject)
    {
        // creating menu actions depending on object type
        if (mContextObject->type() == SCgNode::Type || mContextObject->type() == SCgPair::Type)
        {
            // type changing
            QMenu *menu = mContextMenu->addMenu(tr("Change type"));

            connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(changeType(QAction*)));

            QMenu* constSub = menu->addMenu(tr("Const"));
            QMenu* varSub = menu->addMenu(tr("Var"));

            QString stype;
            SCgAlphabet::SCgObjectTypesMap types;
            SCgAlphabet::SCgObjectTypesMap::const_iterator iter;

            if (mContextObject->type() == SCgNode::Type)
                stype = "node";
            else if (mContextObject->type() == SCgPair::Type)
                stype = "pair";

            SCgAlphabet::getInstance().getObjectTypes(stype, SCgAlphabet::Const, types);
            for (iter = types.begin(); iter != types.end(); ++iter)
                constSub->addAction(iter.value(), iter.key())->setData(QVariant(iter.key()));
            types.clear();
            SCgAlphabet::getInstance().getObjectTypes(stype, SCgAlphabet::Var, types);
            for (iter = types.begin(); iter != types.end(); ++iter)
                varSub->addAction(iter.value(), iter.key())->setData(QVariant(iter.key()));
            types.clear();

            SCgAlphabet::getInstance().getObjectTypes(stype, SCgAlphabet::ConstUnknown, types);
            for (iter = types.begin(); iter != types.end(); ++iter)
                menu->addAction(iter.value(), iter.key())->setData(QVariant(iter.key()));
            types.clear();
        }
    }
Пример #10
0
void TemporalConstraintHeader::paint(
        QPainter *painter,
        const QStyleOptionGraphicsItem *option,
        QWidget *widget)
{
    if(m_state == State::RackHidden)
    {
        auto rect = boundingRect();
        painter->fillRect(rect, ScenarioStyle::instance().ConstraintHeaderRackHidden.getBrush());

        // Fake timenode continuation
        auto color = ScenarioStyle::instance().ConstraintHeaderSideBorder.getColor();
        QPen pen{color, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin};
        painter->setPen(pen);
        painter->drawLine(rect.topLeft(), rect.bottomLeft());
        painter->drawLine(rect.topRight(), rect.bottomRight());
        painter->drawLine(rect.bottomLeft(), rect.bottomRight());
    }

    // Header
    auto font = Skin::instance().SansFont;
    font.setPointSize(10);
    font.setBold(true);

    painter->setFont(font);
    painter->setPen(ScenarioStyle::instance().ConstraintHeaderText.getColor());

    QFontMetrics fm(font);
    int textWidth = fm.width(m_text);

    // If the centered text is hidden, we put it at the left so that it's on the view.
    // We have to compute the visible part of the header
    auto view = scene()->views().first();
    int text_left = view->mapFromScene(mapToScene({m_width / 2. - textWidth / 2., 0})).x();
    int text_right = view->mapFromScene(mapToScene({m_width / 2. + textWidth / 2., 0})).x();
    double x = (m_width - textWidth) / 2.;
    double min_x = 10;
    double max_x = view->width() - 30;

    if(text_left <= min_x)
    {
        // Compute the pixels needed to add to have top-left at 0
        x = x - text_left + min_x;
    }
    else if(text_right >= max_x)
    {
        // Compute the pixels needed to add to have top-right at max
        x = x - text_right + max_x;
    }

    x = std::max(x, 10.);
    double y = 2.5;
    double w = m_width - x;
    double h = ConstraintHeader::headerHeight();


    if(std::abs(m_previous_x - x) > 1)
    {
        m_previous_x = x;
    }
    painter->drawText(m_previous_x,y,w,h, Qt::AlignLeft, m_text);

    if(m_width > 20)
    {
        painter->setPen(ScenarioStyle::instance().ConstraintHeaderBottomLine.getColor());
        painter->drawLine(
                    boundingRect().bottomLeft(),
                    boundingRect().bottomRight());
    }
}
Пример #11
0
void Veturi::aja()
{
    if( !RatapihaIkkuna::getInstance()->skene()->nopeutusKerroin() )
        return; // Jos simulaatio on pysäytetty, ei ajeta


    if( !aktiivinenAkseli() ||  !aktiivinenAkseli()->kiskolla())
        return;

    // Haetaan jkvnopeus, eli suurin nopeus, jolla jkv-laite sallii ajettavan
    paivitaJkvTiedot();

    qreal jkvMs = jkvNopeus() / 3.6;  // JKV-nopeus metreinä sekunnissa
    qreal tavoiteMs = tavoiteNopeus() / 3.6; // Tavoitenopeus m/s


      qreal tavoite = 0.0;

      if( tavoiteNopeus() < 5 )
          tavoite = 0;
      else if( tavoiteMs < jkvMs  )    // JKV ei rajoita
          tavoite = tavoiteMs;
      else
          tavoite = jkvMs;      // JKV rajoittaa!

      QString raidetunnus = aktiivinenAkseli()->kiskolla()->raide()->raidetunnusLiikennepaikalla();


      // Lasketaan ensin uusi nopeus.
      if( tavoite > metriaSekunnissa_)
      {
          // Kiihdytetään
          if( tavoite - metriaSekunnissa_ > kiihtyvyys() * RataIkkuna::rataSkene()->nopeutusKerroin() / 5 )
              metriaSekunnissa_ += kiihtyvyys() * RataIkkuna::rataSkene()->nopeutusKerroin() / 5;
          else
              metriaSekunnissa_ = tavoite;
      }
      else
      {
          // Hidastetaan...
          if( !tavoite && nopeusMs() < 5.0 )       // Jos nopeus alle 1 km/h, niin pysäytetään saman tien
              metriaSekunnissa_ = 0.0;
          else
          {
              if( metriaSekunnissa_ - tavoite > hidastuvuus() * RataIkkuna::rataSkene()->nopeutusKerroin() / 5)   // Normaali jarrutus
                  metriaSekunnissa_ -= hidastuvuus() * RataIkkuna::rataSkene()->nopeutusKerroin() / 5;
              else
                  metriaSekunnissa_ = tavoite;  // Päästään tavotteeseen tällä vuorolla
          }
      }

      qreal liike = metriaSekunnissa_ * RataIkkuna::rataSkene()->nopeutusKerroin() / 5;
        // Tarvittava liike kerrotaan ohjelman nopeuttamisen kertoimella, ja sitten jaetaan
        // päivitysvälillä 1/5 s.


      // Liittämisen varmistaminen, hidastetaan kun ollaan lähellä toista junaa (Onnistuu, kun nopeus max. 35 km/h -- muuten kolari!!! )
      if( liike > 2.0 && nopeus() < 35 )
      {
          QRectF varoalue;
          if( ajopoyta() == 1 )
              varoalue = QRectF(-40.0, -5.0, 40.0, 10.0 );
          else
              varoalue = QRectF(pituus()-20.0, -5.0, 40, 10.0 );
          QList<QGraphicsItem*> lista = scene()->items( mapToScene(varoalue) );
          foreach( QGraphicsItem* item, lista)
          {
              if( dynamic_cast<Vaunu*>(item) && item != this)
                  liike = 2.0;
          }
      }
Пример #12
0
void QgsComposerView::mouseMoveEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  if ( e->buttons() == Qt::NoButton )
  {
    if ( mCurrentTool == Select )
    {
      QGraphicsView::mouseMoveEvent( e );
    }
  }
  else
  {
    QPointF scenePoint = mapToScene( e->pos() );

    switch ( mCurrentTool )
    {
      case Select:
        QGraphicsView::mouseMoveEvent( e );
        break;

      case AddArrow:
      {
        if ( mRubberBandLineItem )
        {
          mRubberBandLineItem->setLine( mRubberBandStartPos.x(), mRubberBandStartPos.y(),  scenePoint.x(),  scenePoint.y() );
        }
        break;
      }

      case AddMap:
      case AddShape:
        //adjust rubber band item
      {
        double x = 0;
        double y = 0;
        double width = 0;
        double height = 0;

        double dx = scenePoint.x() - mRubberBandStartPos.x();
        double dy = scenePoint.y() - mRubberBandStartPos.y();

        if ( dx < 0 )
        {
          x = scenePoint.x();
          width = -dx;
        }
        else
        {
          x = mRubberBandStartPos.x();
          width = dx;
        }

        if ( dy < 0 )
        {
          y = scenePoint.y();
          height = -dy;
        }
        else
        {
          y = mRubberBandStartPos.y();
          height = dy;
        }

        if ( mRubberBandItem )
        {
          mRubberBandItem->setRect( 0, 0, width, height );
          QTransform t;
          t.translate( x, y );
          mRubberBandItem->setTransform( t );
        }
        break;
      }

      case MoveItemContent:
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( scenePoint.x() - mMoveContentStartPos.x(), scenePoint.y() - mMoveContentStartPos.y() );
          composerMap->update();
        }
        break;
      }
      default:
        break;
    }
  }
}
Пример #13
0
void QgsComposerView::mouseReleaseEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPointF scenePoint = mapToScene( e->pos() );

  switch ( mCurrentTool )
  {
    case Select:
    {
      QGraphicsView::mouseReleaseEvent( e );
      break;
    }

    case MoveItemContent:
    {
      if ( mMoveContentItem )
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( 0, 0 );
        }

        double moveX = scenePoint.x() - mMoveContentStartPos.x();
        double moveY = scenePoint.y() - mMoveContentStartPos.y();

        composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) );
        mMoveContentItem->moveContent( -moveX, -moveY );
        composition()->endCommand();
        mMoveContentItem = 0;
      }
      break;
    }
    case AddArrow:
      if ( composition() )
      {
        QPointF scenePoint = mapToScene( e->pos() );
        QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
        QgsComposerArrow* composerArrow = new QgsComposerArrow( mRubberBandStartPos, QPointF( snappedScenePoint.x(), snappedScenePoint.y() ), composition() );
        composition()->addComposerArrow( composerArrow );
        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) );
      }
      break;

    case AddShape:
      if ( !mRubberBandItem || mRubberBandItem->rect().width() < 0.1 || mRubberBandItem->rect().width() < 0.1 )
      {
        scene()->removeItem( mRubberBandItem );
        delete mRubberBandItem;
        mRubberBandItem = 0;
        return;
      }
      if ( composition() )
      {
        QgsComposerShape* composerShape = new QgsComposerShape( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height(), composition() );
        composition()->addComposerShape( composerShape );
        scene()->removeItem( mRubberBandItem );
        delete mRubberBandItem;
        mRubberBandItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerShape, tr( "Shape added" ) );
      }
      break;

    case AddMap:
      if ( !mRubberBandItem || mRubberBandItem->rect().width() < 0.1 || mRubberBandItem->rect().width() < 0.1 )
      {
        if ( mRubberBandItem )
        {
          scene()->removeItem( mRubberBandItem );
          delete mRubberBandItem;
          mRubberBandItem = 0;
        }
        return;
      }
      if ( composition() )
      {
        QgsComposerMap* composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
        composition()->addComposerMap( composerMap );
        scene()->removeItem( mRubberBandItem );
        delete mRubberBandItem;
        mRubberBandItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) );
      }
      break;

    default:
      break;
  }
}
Пример #14
0
QRectF Item::realBoundingRect() const
{
	return mapToScene(calcNecessaryBoundingRect()).boundingRect();
}
Пример #15
0
/*---------------------------------------------------------------------------*/
void Car::checkLightForward( ) 
{

    bool bForward = true;

	QPointF curLoc = mapToScene( 0, 0 );

	if ( curLoc == lightCr1BSN || curLoc == lightCr1BSS ) {
		if ( !ableToForward( pLightAtCr1, eNS ) ) {
		//if ( !pLightAtCr1->ableNS ) {
		//if ( pLightAtCr1->getLightStatus( eNS ) == trafficLightRed ) {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = false;
		}
		else {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = true;
		}

	}
	else if ( curLoc == lightCr1RHW || curLoc == lightCr1RHE ) {
		if ( !ableToForward( pLightAtCr1, eWE ) ) {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = false;
		}
		else {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = true;
		}
	}
	else if ( curLoc == lightCr2TBN || curLoc == lightCr2TBS ) {
		if ( !ableToForward( pLightAtCr2, eNS ) ) {
			bForward = false;
			//setPos( mapToParent( 0, 0.5 ) );
		}
		else {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = true;
		}
	}
	else if ( curLoc == lightCr2RHW || curLoc == lightCr2RHE ) {
		if ( !ableToForward( pLightAtCr2, eWE ) ) {
			bForward = false;
			//setPos( mapToParent( 0, 0.5 ) );
		}
		else {
			//setPos( mapToParent( 0, 0.5 ) );
			bForward = true;
		}
	}
	else {
		//setPos( mapToParent( 0, 0.5 ) );
		//*bForward = true;
	//}

		QPointF curLocFront = mapToScene( 0, 15 );
		QGraphicsItem* pfront = scene()->itemAt( curLocFront );
		if (pfront != 0) {
			bForward = false;
		}
		else {
			bForward = true;
		}
	}

    //  Go forward if bForward is ture
    if ( bForward ) {
		setPos( mapToParent( 0, 0.5 ) );
    }

}
Пример #16
0
QPointF WeightEditProxy::getNodeCenter() const
{
	return mapToScene(QPointF(nodeRect.left() + nodeRect.width()/2, nodeRect.top() + nodeRect.height()/2));
}//getNodeCenter
Пример #17
0
QPointF Soma::getCenter() const
{
	return mapToScene(QPointF(rect().left() + rect().width()/2, rect().top() + rect().height()/2));
}
Пример #18
0
void QgsComposerView::keyPressEvent( QKeyEvent * e )
{
  if ( e->key() == Qt::Key_Shift )
  {
    mShiftKeyPressed = true;
  }

  if ( !composition() )
  {
    return;
  }

  QList<QgsComposerItem*> composerItemList = composition()->selectedComposerItems();
  QList<QgsComposerItem*>::iterator itemIt = composerItemList.begin();

  if ( e->matches( QKeySequence::Copy ) || e->matches( QKeySequence::Cut ) )
  {
    QDomDocument doc;
    QDomElement documentElement = doc.createElement( "ComposerItemClipboard" );
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      // copy each item in a group
      QgsComposerItemGroup* itemGroup = dynamic_cast<QgsComposerItemGroup*>( *itemIt );
      if ( itemGroup && composition() )
      {
        QSet<QgsComposerItem*> groupedItems = itemGroup->items();
        QSet<QgsComposerItem*>::iterator it = groupedItems.begin();
        for ( ; it != groupedItems.end(); ++it )
        {
          ( *it )->writeXML( documentElement, doc );
        }
      }
      ( *itemIt )->writeXML( documentElement, doc );
      if ( e->matches( QKeySequence::Cut ) )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
    doc.appendChild( documentElement );
    QMimeData *mimeData = new QMimeData;
    mimeData->setData( "text/xml", doc.toByteArray() );
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setMimeData( mimeData );
  }

  if ( e->matches( QKeySequence::Paste ) )
  {
    QDomDocument doc;
    QClipboard *clipboard = QApplication::clipboard();
    if ( doc.setContent( clipboard->mimeData()->data( "text/xml" ) ) )
    {
      QDomElement docElem = doc.documentElement();
      if ( docElem.tagName() == "ComposerItemClipboard" )
      {
        if ( composition() )
        {
          QPointF pt = mapToScene( mapFromGlobal( QCursor::pos() ) );
          composition()->addItemsFromXML( docElem, doc, true, &pt );
        }
      }
    }
  }

  //delete selected items
  if ( e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      if ( composition() )
      {
        composition()->removeComposerItem( *itemIt );
      }
    }
  }

  else if ( e->key() == Qt::Key_Left )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( -1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Right )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 1.0, 0.0 );
    }
  }
  else if ( e->key() == Qt::Key_Down )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, 1.0 );
    }
  }
  else if ( e->key() == Qt::Key_Up )
  {
    for ( ; itemIt != composerItemList.end(); ++itemIt )
    {
      ( *itemIt )->move( 0.0, -1.0 );
    }
  }
}
Пример #19
0
/*!\brief reimplementation of the mousePressEvent
 *
 * ...
 */
void LaunchFileView::mousePressEvent(QMouseEvent *event)
{

    if (event->button() == Qt::MidButton) {
        _handScrolling = true;
        _handScrollingOrigin = QPoint(event->pos());
        _handScrollingValueX = horizontalScrollBar()->value();
        _handScrollingValueY = verticalScrollBar()->value();
        _savedCursor = viewport()->cursor();
        viewport()->setCursor(Qt::ClosedHandCursor);
        event->accept();
        QGraphicsView::mousePressEvent(event);
        return;
    }
    if (itemAt((event->pos()))){ //else tool crashes on first click
        if (event->button() == Qt::LeftButton){
            if (selectedBox){
                selectedBox->setZValue(0);
                selectedBox->setColor(Qt::black);
                if (itemAt((event->pos()))->type() == NodeItem::Type) {  //NodeItem::Type means the node itself
                    selectedBox= qgraphicsitem_cast<NodeItem *>(itemAt((event->pos())));
                }else if (itemAt(event->pos())->type() == 8 && itemAt(event->pos())->parentItem()->type() == NodeItem::Type){   //8 means the textitem in the node
                    selectedBox= qgraphicsitem_cast<NodeItem *>(itemAt((event->pos()))->parentItem());
                }
                selectedBox->setZValue(100);
            }
            switch (myMode) {
            case DragItem:

                QGraphicsView::mousePressEvent(event);
                event->setAccepted(true);// tell the base class we are handling this event

                break;
                //! [6] //! [7]
            case InsertLine:
                if (itemAt((event->pos()))->type() == NodeItem::Type || (itemAt(event->pos())->type() == 8 && itemAt(event->pos())->parentItem()->type() == NodeItem::Type)) {
                    line = new QGraphicsLineItem(QLineF(mapToScene(event->pos()),
                                                        mapToScene(event->pos())));

                    scene()->addItem(line);
                }

                event->setAccepted(true);// tell the base class we are handling this event

                QGraphicsView::mousePressEvent(event);
                break;
            case DeleteItem:

                //qDebug()<<itemAt((event->pos()));


                if (itemAt((event->pos()))->type() == 65550) { //Arrowtype RemapArrow::Type
                    RemapArrow *arrow = qgraphicsitem_cast<RemapArrow *>(itemAt((event->pos())));
//                    RemapItem *item;
//                    for (int i=0; i< arrow->startItem()->remapItems.count();i++){
//                        item = arrow->startItem()->remapItems.at(i);


//                        if (item->getFrom()==arrow->getFrom() && item->getTo()==arrow->getTo()){
//                            arrow->startItem()->removeRemapItem(item);
//                        }

//                    }
                    arrow->startItem()->removeArrow(arrow);
                    arrow->endItem()->removeArrow(arrow);
                    scene()->removeItem(itemAt((event->pos())));
                    delete itemAt((event->pos()));
                }
                event->accept();
                break;
            default:
                break;
            }
        }
    }else{
    }


}
Пример #20
0
void QgsComposerView::mousePressEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPointF scenePoint = mapToScene( e->pos() );
  QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );

  //lock/unlock position of item with right click
  if ( e->button() == Qt::RightButton )
  {
    QgsComposerItem* selectedItem = composition()->composerItemAt( scenePoint );
    if ( selectedItem )
    {
      bool lock = selectedItem->positionLock() ? false : true;
      selectedItem->setPositionLock( lock );
      selectedItem->update();
      //make sure the new cursor is correct
      QPointF itemPoint = selectedItem->mapFromScene( scenePoint );
      selectedItem->updateCursor( itemPoint );
    }
    return;
  }

  switch ( mCurrentTool )
  {
      //select/deselect items and pass mouse event further
    case Select:
    {
      if ( !mShiftKeyPressed ) //keep selection if shift key pressed
      {
        composition()->clearSelection();
      }

      //select topmost item at position of event
      QgsComposerItem* selectedItem = composition()->composerItemAt( scenePoint );
      if ( !selectedItem )
      {
        break;
      }

      selectedItem->setSelected( true );
      QGraphicsView::mousePressEvent( e );
      emit selectedItemChanged( selectedItem );
      break;
    }

    case MoveItemContent:
    {
      //store item as member if it is selected and cursor is over item
      QgsComposerItem* item = dynamic_cast<QgsComposerItem *>( itemAt( e->pos() ) );
      if ( item )
      {
        mMoveContentStartPos = scenePoint;
      }
      mMoveContentItem = item;
      break;
    }

    case AddArrow:
    {
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem = new QGraphicsLineItem( snappedScenePoint.x(), snappedScenePoint.y(), snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem->setZValue( 100 );
      scene()->addItem( mRubberBandLineItem );
      scene()->update();
      break;
    }

    //create rubber band for map and ellipse items
    case AddMap:
    case AddShape:
    {
      QTransform t;
      mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 );
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      t.translate( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandItem->setTransform( t );
      mRubberBandItem->setZValue( 100 );
      scene()->addItem( mRubberBandItem );
      scene()->update();
    }
    break;

    case AddLabel:
      if ( composition() )
      {
        QgsComposerLabel* newLabelItem = new QgsComposerLabel( composition() );
        newLabelItem->setText( tr( "Quantum GIS" ) );
        newLabelItem->adjustSizeToText();
        newLabelItem->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLabelItem->rect().width(), newLabelItem->rect().height() ) );
        composition()->addComposerLabel( newLabelItem );
        emit actionFinished();
        composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) );
      }
      break;

    case AddScalebar:
      if ( composition() )
      {
        QgsComposerScaleBar* newScaleBar = new QgsComposerScaleBar( composition() );
        newScaleBar->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 20, 20 ) );
        composition()->addComposerScaleBar( newScaleBar );
        QList<const QgsComposerMap*> mapItemList = composition()->composerMapItems();
        if ( mapItemList.size() > 0 )
        {
          newScaleBar->setComposerMap( mapItemList.at( 0 ) );
        }
        newScaleBar->applyDefaultSize(); //4 segments, 1/5 of composer map width
        emit actionFinished();
        composition()->pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) );
      }
      break;

    case AddLegend:
    {
      if ( composition() )
      {
        QgsComposerLegend* newLegend = new QgsComposerLegend( composition() );
        newLegend->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLegend->rect().width(), newLegend->rect().height() ) );
        composition()->addComposerLegend( newLegend );
        newLegend->updateLegend();
        emit actionFinished();
        composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) );
      }
      break;
    }
    case AddPicture:
      if ( composition() )
      {
        QgsComposerPicture* newPicture = new QgsComposerPicture( composition() );
        newPicture->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 30, 30 ) );
        composition()->addComposerPicture( newPicture );
        emit actionFinished();
        composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) );
      }
      break;
    case AddTable:
      if ( composition() )
      {
        QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( composition() );
        newTable->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 50, 50 ) );
        composition()->addComposerTable( newTable );
        emit actionFinished();
        composition()->pushAddRemoveCommand( newTable, tr( "Table added" ) );
      }
      break;
    default:
      break;
  }
}
Пример #21
0
void QLineItem::compile(QSqlDatabase &db, int nSceneId,int &count,int index)
{
    count++;

    //QBasicGraphicsItem::compile(db, nSceneId, count, index);

    QSqlQuery sqlquery(db);
    sqlquery.prepare("INSERT INTO line(nItemNumber ,nSceneId ,eLineClass ,eLineType ,nLineWidth ,"
                     "nLineColor ,eLineArrow ,nAlpha , eLinePointType ,nZvalue,nCollidindId,"
                     "nStartX ,nStartY ,nWidth ,nHeight )"
                     "VALUES (:nItemNumber ,:nSceneId ,:eLineClass ,:eLineType ,:nLineWidth ,"
                     ":nLineColor ,:eLineArrow ,:nAlpha , :eLinePointType,:nZvalue,:nCollidindId,"
                     ":nStartX ,:nStartY ,:nWidth ,:nHeight)");
    sqlquery.bindValue(":nItemNumber",QVariant(count));// 表 id
    sqlquery.bindValue(":nSceneId",QVariant(nSceneId));// 所在场景 id
    sqlquery.bindValue(":eLineClass",QVariant(1)); //1 代表类型为直线
    sqlquery.bindValue(":eLineType",QVariant(nLineType+1));// 线形
    sqlquery.bindValue(":nLineWidth",QVariant(getLineWidth()));// 线宽
    sqlquery.bindValue(":nLineColor",QVariant(ColorToInt(getLineColor()))); //颜色
    sqlquery.bindValue(":eLineArrow",QVariant(m_eLineEndArrowType+1));// 箭头
    sqlquery.bindValue(":nAlpha",QVariant(getAlpha()));// 透明度
    sqlquery.bindValue(":eLinePointType",QVariant(m_eLineEndArrowType+1)); //端点类型

    sqlquery.bindValue(":nZvalue",QVariant(zValue()));//层次

    sqlquery.bindValue(":nCollidindId",QVariant(index));//碰撞ID

    QRectF rect = sceneBoundingRect();
    if(getLineWidth() == 1)
    {
        sqlquery.bindValue(":nStartX",QVariant(rect.x()-1));//x
        sqlquery.bindValue(":nStartY",QVariant(rect.y()-1));//y
        sqlquery.bindValue(":nWidth",QVariant(rect.width()+2));//w
        sqlquery.bindValue(":nHeight",QVariant(rect.height()+2));//h
    }
    else
    {
        sqlquery.bindValue(":nStartX",QVariant(rect.x()));//x
        sqlquery.bindValue(":nStartY",QVariant(rect.y()));//y
        sqlquery.bindValue(":nWidth",QVariant(rect.width()));//w
        sqlquery.bindValue(":nHeight",QVariant(rect.height()));//h
    }

    bool result = false;
    result = sqlquery.exec();
    qDebug() << "insert line table :"<<result;

    sqlquery.prepare("INSERT INTO point(nItemId,nPosX,nPosY,nOrder,ePointType)"
                     "VALUES (:nItemId ,:nPosX ,:nPosY ,:nOrder ,:ePointType )");
    for(int i=0; i<2; i++)
    {
        QPointF pt = this->path().pointAtPercent(i);
        pt = mapToScene(pt);
        sqlquery.bindValue(":nItemId",QVariant(count));// item表 id
        sqlquery.bindValue(":nPosX",QVariant((int)pt.x()));// X
        sqlquery.bindValue(":nPosY",QVariant((int)pt.y())); //Y
        sqlquery.bindValue(":nOrder",QVariant(i));// 顺序
        sqlquery.bindValue(":ePointType",QVariant(1));// 显示点
        result = sqlquery.exec();
        qDebug() << "insert point table :"<<result;
    }

    SamDrawScene *pScene = dynamic_cast<SamDrawScene *>(scene());
    if(pScene && pScene->nIsSceneOrWindow == 2)
    {
        //是自定义键盘的item
        //先新建键盘——item关联表 item表在派生类中创建

        //QSqlQuery sqlquery(db);

        sqlquery.prepare("INSERT INTO kbAndItem(nKeyBoardId , nItemId ,nId,nItemTableType ) "
                         "VALUES (:nKeyBoardId ,:nItemId ,:nId,:nItemTableType)");
        sqlquery.bindValue(":nKeyBoardId",QVariant(nSceneId));
        sqlquery.bindValue(":nItemId",QVariant(count));
        sqlquery.bindValue(":nId",QVariant(id()));
        sqlquery.bindValue(":nItemTableType",QVariant((int)SAM_DRAW_OBJECT_LINE));

        bool result = false;
        result = sqlquery.exec();
        qDebug() << "insert kbAndItem table :"<<result;

    }
    if(pScene && pScene->nIsSceneOrWindow != 2)
    {
        //窗口或者场景item
        //先新建键盘——item关联表
        //item表在派生类中创建

        //QSqlQuery sqlquery(db);

        sqlquery.prepare("INSERT INTO sceneAndItem(nSceneId,nItemId,nId,nItemTableType)"
                         "VALUES(:nSceneId,:nItemId,:nId,:nItemTableType)");
        sqlquery.bindValue(":nSceneId",QVariant(nSceneId));
        sqlquery.bindValue(":nItemId",QVariant(count));
        sqlquery.bindValue(":nId",QVariant(id()));
        //int t = this->GroupType();
        sqlquery.bindValue(":nItemTableType",QVariant((int)SAM_DRAW_OBJECT_LINE));

        bool result = false;
        result = sqlquery.exec();
        qDebug() << "insert sceneAndItem table :"<<result;
    }
}
Пример #22
0
void Cell :: mousePressEvent( QGraphicsSceneMouseEvent * )
{
    if ( !moving )
    {
        QPointF localCellCenter( SELL_SIZE/2, SELL_SIZE/2 );
        QPointF sceneCellCenter = mapToScene( localCellCenter );

        const bool top = ( localCellCenter.y() == sceneCellCenter.y() );
        const bool left = ( localCellCenter.x() == sceneCellCenter.x() );
        const bool bottom = ( sceneCellCenter.y() == SELL_SIZE * boardSize - SELL_SIZE/2 );
        const bool right = ( sceneCellCenter.x() == SELL_SIZE * boardSize - SELL_SIZE/2 );

        QPointF upCenterPoint( sceneCellCenter.x(), sceneCellCenter.y() - SELL_SIZE );
        QPointF downCenterPoint( sceneCellCenter.x(), sceneCellCenter.y() + SELL_SIZE );
        QPointF leftCenterPoint( sceneCellCenter.x() - SELL_SIZE, sceneCellCenter.y() );
        QPointF rightCenterPoint( sceneCellCenter.x() + SELL_SIZE, sceneCellCenter.y() );

        QList< QGraphicsItem *> cellList;

        if ( !top )
        {
            cellList = scene()->items( upCenterPoint );
            if ( cellList.size() == 0 )
            {
                newPosition = mapToParent( 0, -SELL_SIZE );
                moving = true;
                QSound::play( ":/sounds/Sounds/move.wav" );
            }
        }

        if ( !left )
        {
            cellList = scene()->items( leftCenterPoint );
            if ( cellList.size() == 0 )
            {
                newPosition = mapToParent( -SELL_SIZE, 0 );
                moving = true;
                QSound::play( ":/sounds/Sounds/move.wav" );
            }
        }

        if ( !bottom )
        {
            cellList = scene()->items( downCenterPoint );
            if ( cellList.size() == 0 )
            {
                newPosition = mapToParent( 0, SELL_SIZE );
                moving = true;
                QSound::play( ":/sounds/Sounds/move.wav" );
            }
        }

        if ( !right )
        {
            cellList = scene()->items( rightCenterPoint );
            if ( cellList.size() == 0 )
            {
                newPosition = mapToParent( SELL_SIZE, 0 );
                moving = true;
                QSound::play( ":/sounds/Sounds/move.wav" );
            }
        }
    }
}
Пример #23
0
void Wire::updatePosition()
{
    //if(polygon().isEmpty())
    //    return;
    //polygon().pop_front();
    //polygon().pop_back();


//    QPolygonF poly;
//    poly << mapFromItem(d_source, 0, 0);

//    foreach(QPointF point, polygon())
//    {
//        //qDebug() << point.x() << point.y();
//        if(point != polygon().front() && point != polygon().back())
//            poly << point;

//    }

//    poly << mapFromItem(d_destination, 0, 0);
//    setPolygon(poly);
    //lines.clear();
    QLineF line(mapFromItem(d_source, 0, 0), mapFromItem(d_destination, 0, 0));
    QPointF src = mapFromItem(d_source, 0, 0);
    QPointF dest = mapFromItem(d_destination, 0, 0);
    //d_half = src + (dest-src)/2;
    //QPointF oldHalf = mapToItem(segment,d_half);

    //src.rx()-=20*source()->posFactor();
    // dest.rx()+=2*(1/destination()->posFactor());
    // QPointF half = src + (dest-src)/2;




    QPainterPath path(src);
    if(src.x() > dest.x()) {
        QPointF newHalf = mapToScene(src + (dest-src)/2);
        segment->setPos(newHalf.x(),segment->y());
        QPointF seg = mapFromItem(segment, 0, 0);
        path.lineTo( QPointF(src.x(),seg.y()));
        path.lineTo(QPointF(dest.x(),seg.y()));
        path.lineTo(dest);
    } else {
        QPointF newHalf = mapToScene(src + (dest-src)/2);
        segment->setPos(segment->x(),newHalf.y());
        QPointF seg = mapFromItem(segment, 0, 0);
        path.lineTo(QPointF(seg.x(),src.y()));
        path.lineTo(QPointF(seg.x(),dest.y()));
        path.lineTo(dest);
    }

    setPath(path);


//    QPolygonF poly;

//    if(source.x() > dest.x())
//        poly << source << QPointF(source.x(),half.y())
//                 << QPointF(dest.x(),half.y()) << dest;
//    else
//        poly << source << QPointF(half.x(),source.y())
//                 << QPointF(half.x(),dest.y()) << dest;

//    setPolygon(poly);
    //QLineF linex(line.p1(), QPointF(line.x1()+line.dx(),line.y1()));
    //QLineF liney(linex.p2(), QPointF(linex.x2(),line.y1()+line.dy()));
    //lines.append(linex);
    //lines.append(liney);
    //setLine(line);
}
Пример #24
0
// convert viewport coordinate to the original image (not scaled).
QRect ImageView::viewportToScene(const QRect& rect) {
  // QPolygon poly = mapToScene(imageItem_->rect());
  QPoint topLeft = mapToScene(rect.topLeft()).toPoint();
  QPoint bottomRight = mapToScene(rect.bottomRight()).toPoint();
  return QRect(topLeft, bottomRight);
}
Пример #25
0
void QgsComposerView::wheelZoom( QWheelEvent * event )
{
  //get mouse wheel zoom behaviour settings
  QSettings mySettings;
  int wheelAction = mySettings.value( "/qgis/wheel_action", 2 ).toInt();
  double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble();

  if (( QgsMapCanvas::WheelAction )wheelAction == QgsMapCanvas::WheelNothing )
  {
    return;
  }

  if ( event->modifiers() & Qt::ControlModifier )
  {
    //holding ctrl while wheel zooming results in a finer zoom
    zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 10.0;
  }

  //caculate zoom scale factor
  bool zoomIn = event->delta() > 0;
  double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor );

  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

  //transform the mouse pos to scene coordinates
  QPointF scenePoint = mapToScene( event->pos() );

  //adjust view center according to wheel action setting
  switch (( QgsMapCanvas::WheelAction )wheelAction )
  {
    case QgsMapCanvas::WheelZoomAndRecenter:
    {
      centerOn( scenePoint.x(), scenePoint.y() );
      break;
    }

    case QgsMapCanvas::WheelZoomToMouseCursor:
    {
      QgsPoint oldCenter( visibleRect.center() );
      QgsPoint newCenter( scenePoint.x() + (( oldCenter.x() - scenePoint.x() ) * scaleFactor ),
                          scenePoint.y() + (( oldCenter.y() - scenePoint.y() ) * scaleFactor ) );
      centerOn( newCenter.x(), newCenter.y() );
      break;
    }

    default:
      break;
  }

  //zoom composition
  if ( zoomIn )
  {
    scale( zoomFactor, zoomFactor );
  }
  else
  {
    scale( 1 / zoomFactor, 1 / zoomFactor );
  }

  //update composition for new zoom
  emit zoomLevelChanged();
  updateRulers();
  update();
  //redraw cached map items
  QList<QGraphicsItem *> itemList = composition()->items();
  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
  for ( ; itemIt != itemList.end(); ++itemIt )
  {
    QgsComposerMap* mypItem = dynamic_cast<QgsComposerMap *>( *itemIt );
    if (( mypItem ) && ( mypItem->previewMode() == QgsComposerMap::Render ) )
    {
      mypItem->updateCachedImage();
    }
  }
}
Пример #26
0
void DragWidgetGrid::dropEvent(QDropEvent *event)
{
    if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
        QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
        QDataStream dataStream(&itemData, QIODevice::ReadOnly);
 
        QPixmap pixmap;
        QPoint offset;
        dataStream >> pixmap >> offset;
		
		ScenePixmapItem * item;

        if (event->source() == this) {
            event->setDropAction(Qt::MoveAction);
            event->accept();
        } else {
            event->acceptProposedAction();
        }

		if(svg_list->isConnectorBeingDragged){
			qDebug() << "e um connector";
			svg_list->isConnectorBeingDragged = false;
			
			underItem = itemAt(event->pos());
			if(underItem){
				item = new ScenePixmapItem(NULL,&scene);
		
				item->setPixmap(pixmap);
				
				item->setPos(underItem->scenePos());
				qDebug() << "no no no :S";
				if(detectBorderCollisions(item)){
					qDebug() << "we collided";

					item->setZValue(underItem->zValue()+1);
										
					item->setCursor(Qt::ClosedHandCursor);
		
					item->setData(ObjectID,event->mimeData()->text());
				}
				else scene.removeItem(item);			
			}
			else return;
		}else{

			item = new ScenePixmapItem(NULL,&scene);
		
			item->setPixmap(pixmap);
		
			item->setPos(item->pos() + mapToScene(event->pos() - offset));
		
			item->setCursor(Qt::ClosedHandCursor);
		
			item->setData(ObjectID,event->mimeData()->text());

		}
		item->setData(Sheared,0);
		qreal pixmap_width = pixmap.width();
		pixmap_width /= ScalingToReal;
		qreal pixmap_height = pixmap.height();
		pixmap_height /= ScalingToReal;
		QString i_size = QString("x: %1 | y: %2").arg(pixmap_width).arg(pixmap_height);
		if( MaskSheared && item->data(Sheared).toInt()  )
			item->setToolTip( trUtf8("Não disponível") );
		else
			item->setToolTip( i_size );
		item->setData(ObjectX,pixmap_width);
		item->setData(ObjectY,pixmap_height);
		
    } else {
Пример #27
0
void QgsComposerView::mouseMoveEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  mMouseCurrentXY = e->pos();
  //update cursor position in composer status bar
  emit cursorPosChanged( mapToScene( e->pos() ) );

  updateRulers();
  if ( mHorizontalRuler )
  {
    mHorizontalRuler->updateMarker( e->posF() );
  }
  if ( mVerticalRuler )
  {
    mVerticalRuler->updateMarker( e->posF() );
  }

  if ( mPanning )
  {
    //panning, so scroll view
    horizontalScrollBar()->setValue( horizontalScrollBar()->value() - ( e->x() - mMouseLastXY.x() ) );
    verticalScrollBar()->setValue( verticalScrollBar()->value() - ( e->y() - mMouseLastXY.y() ) );
    mMouseLastXY = e->pos();
    return;
  }
  else if ( e->buttons() == Qt::NoButton )
  {
    if ( mCurrentTool == Select )
    {
      QGraphicsView::mouseMoveEvent( e );
    }
  }
  else
  {
    QPointF scenePoint = mapToScene( e->pos() );

    if ( mMarqueeSelect || mMarqueeZoom )
    {
      updateRubberBand( scenePoint );
      return;
    }

    switch ( mCurrentTool )
    {
      case Select:
        QGraphicsView::mouseMoveEvent( e );
        break;

      case AddArrow:
      {
        if ( mRubberBandLineItem )
        {
          mRubberBandLineItem->setLine( mRubberBandStartPos.x(), mRubberBandStartPos.y(),  scenePoint.x(),  scenePoint.y() );
        }
        break;
      }

      case AddMap:
      case AddRectangle:
      case AddTriangle:
      case AddEllipse:
      case AddHtml:
        //adjust rubber band item
      {
        updateRubberBand( scenePoint );
        break;
      }

      case MoveItemContent:
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( scenePoint.x() - mMoveContentStartPos.x(), scenePoint.y() - mMoveContentStartPos.y() );
          composerMap->update();
        }
        break;
      }
      default:
        break;
    }
  }
}
Пример #28
0
void StateDiagramView::dropEvent(QDropEvent * e)
{
    BrowserState * mach =
        BrowserState::get_machine(the_canvas()->browser_diagram());
    BrowserNode * bn;
    QPointF p = mapToScene(e->pos());

    if ((bn = UmlDrag::decode(e, UmlState, TRUE)) != 0) {
        if (the_canvas()->already_drawn(bn))
            msg_information("Douml", TR("already drawn"));
        else if (BrowserState::get_machine(bn) != mach)
            msg_information("Douml", TR("illegal"));
        else {
            history_save();

            // mettre des contraintes sur la validite ?
            StateCanvas * c =
                new StateCanvas(bn, the_canvas(), p.x(), p.y());

            history_protected = TRUE;
            c->show();
            c->upper();
            canvas()->update();
            StateCanvas::force_inside(c, TRUE);
            canvas()->update();
            history_protected = FALSE;
            window()->package_modified();
        }
    }
    else if ((bn = UmlDrag::decode(e, UmlPackage)) != 0) {
        history_save();

        PackageCanvas * pk =
            new PackageCanvas(bn, the_canvas(), p.x(), p.y(), 0);

        history_protected = TRUE;
        pk->show();
        pk->upper();
        canvas()->update();
        window()->package_modified();
    }
    else if ((bn = UmlDrag::decode(e, UmlPseudoState, TRUE)) != 0) {
        if (the_canvas()->already_drawn(bn))
            msg_information("Douml", TR("already drawn"));
        else if (BrowserState::get_machine(bn) != mach)
            msg_information("Douml", TR("illegal"));
        else {
            history_save();

            // mettre des contraintes sur la validite ?
            PseudoStateCanvas * c =
                new PseudoStateCanvas(bn, the_canvas(), p.x(), p.y());

            history_protected = TRUE;
            c->show();
            c->upper();
            StateCanvas::force_inside(c, FALSE);
            canvas()->update();
            history_protected = FALSE;
            window()->package_modified();
        }
    }
    else if ((bn = UmlDrag::decode(e, UmlStateAction, TRUE)) != 0) {
        if (the_canvas()->already_drawn(bn))
            msg_information("Douml", TR("already drawn"));
        else if (BrowserState::get_machine(bn) != mach)
            msg_information("Douml", TR("illegal"));
        else {
            history_save();

            // mettre des contraintes sur la validite ?
            StateActionCanvas * c =
                new StateActionCanvas(bn, the_canvas(), p.x(), p.y());

            history_protected = TRUE;
            c->show();
            c->upper();
            StateCanvas::force_inside(c, FALSE);
            canvas()->update();
            history_protected = FALSE;
            window()->package_modified();
        }
    }
    else if ((bn = UmlDrag::decode(e, UmlTransition, TRUE)) != 0) {
        history_save();

        history_protected = TRUE;
        TransitionCanvas::drop(bn, the_canvas());
        canvas()->update();
        history_protected = FALSE;
    }
    else if (((bn = UmlDrag::decode(e, UmlClassDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlUseCaseDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlSeqDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlColDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlObjectDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlStateDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlComponentDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlDeploymentDiagram)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlStateDiagram, TRUE)) != 0) ||
             ((bn = UmlDrag::decode(e, UmlActivityDiagram, TRUE)) != 0)) {
        history_save();

        IconCanvas * ic = new IconCanvas(bn, the_canvas(), p.x(), p.y(), 0);

        history_protected = TRUE;
        ic->show();
        ic->upper();

        canvas()->update();
        history_protected = FALSE;
        window()->package_modified();
    }
}
Пример #29
0
//! [4]
void Mouse::advance(int step)
{
    if (!step)
        return;

    if (mReplay) {
         std::cout << "___________________" <<mPosList->size() << std::endl;
        if (mI < mPosList->size()) {
            setPos(mPosList->at(mI));
            std::cout << mPosList->at(mI).x() << "---" << mPosList->at(mI).y() << "---" << x() << "---" << y() << std::endl;
            mI++;
        } else {
            finished = true;
            emit animationFinished();
        }
    } else {
//! [4]
    // Don't move too far away
//! [5]
    QLineF lineToCenter(QPointF(0, 0), mapFromScene(0, 0));
    if (lineToCenter.length() > 150) {
        qreal angleToCenter = ::acos(lineToCenter.dx() / lineToCenter.length());
        if (lineToCenter.dy() < 0)
            angleToCenter = TwoPi - angleToCenter;
        angleToCenter = normalizeAngle((Pi - angleToCenter) + Pi / 2);

        if (angleToCenter < Pi && angleToCenter > Pi / 4) {
            // Rotate left
            angle += (angle < -Pi / 2) ? 0.25 : -0.25;
        } else if (angleToCenter >= Pi && angleToCenter < (Pi + Pi / 2 + Pi / 4)) {
            // Rotate right
            angle += (angle < Pi / 2) ? 0.25 : -0.25;
        }
    } else if (::sin(angle) < 0) {
        angle += 0.25;
    } else if (::sin(angle) > 0) {
        angle -= 0.25;
//! [5] //! [6]
    }
//! [6]

    // Try not to crash with any other mice
//! [7]
    QList<QGraphicsItem *> dangerMice = scene()->items(QPolygonF()
                                                       << mapToScene(0, 0)
                                                       << mapToScene(-30, -50)
                                                       << mapToScene(30, -50));
    foreach (QGraphicsItem *item, dangerMice) {
        if (item == this)
            continue;

        QLineF lineToMouse(QPointF(0, 0), mapFromItem(item, 0, 0));
        qreal angleToMouse = ::acos(lineToMouse.dx() / lineToMouse.length());
        if (lineToMouse.dy() < 0)
            angleToMouse = TwoPi - angleToMouse;
        angleToMouse = normalizeAngle((Pi - angleToMouse) + Pi / 2);

        if (angleToMouse >= 0 && angleToMouse < Pi / 2) {
            // Rotate right
            angle += 0.5;
        } else if (angleToMouse <= TwoPi && angleToMouse > (TwoPi - Pi / 2)) {
            // Rotate left
            angle -= 0.5;
//! [7] //! [8]
        }
//! [8] //! [9]
    }
//! [9]

    // Add some random movement
//! [10]
    if (dangerMice.size() > 1 && (qrand() % 10) == 0) {
        if (qrand() % 1)
            angle += (qrand() % 100) / 500.0;
        else
            angle -= (qrand() % 100) / 500.0;
    }
//! [10]

//! [11]
    speed += (-50 + qrand() % 100) / 100.0;

    qreal dx = ::sin(angle) * 10;
    mouseEyeDirection = (qAbs(dx / 5) < 1) ? 0 : dx / 5;

    setRotation(rotation() + dx);
    setPos(mapToParent(0, -(3 + sin(speed) * 3)));
    std::cout << QTime().elapsed() << ":" << data(0).toString().toLocal8Bit().constData() << ":" << x() << ":" << y() <<std::endl;
    }
}
Пример #30
0
void StateDiagramView::mousePressEvent(QMouseEvent * e)
{
    QPoint diagramPoint(e->x(), e->y());
    QPointF scenePoint = mapToScene(diagramPoint);
    if (!window()->frozen()) {
        UmlCode action = window()->buttonOn();

        switch (action) {
        case UmlState: {
            history_protected = TRUE;
            unselect_all();
            window()->selectOn();
            history_save();

            QGraphicsItem * ci = the_canvas()->collision(scenePoint.toPoint());
            DiagramItem * di;
            bool specified = ((ci != 0) &&
                              ((di = QCanvasItemToDiagramItem(ci)) != 0) &&
                              (di->typeUmlCode() == UmlState) &&
                              ((BrowserState *)((StateCanvas *) di)->get_bn())->may_contains(action));
            BrowserNode * parent;

            if (specified) {
                if ((parent = ((StateCanvas *) di)->pointed_region(scenePoint.toPoint())) == 0)
                    parent = ((StateCanvas *) di)->get_bn();
            }
            else
                parent = (BrowserNode *) window()->browser_diagram()->parent();

            BrowserNode * b = BrowserState::get_state(parent);

            if (b != 0) {
                if (the_canvas()->already_drawn(b)) {
                    msg_information("Douml", TR("already drawn"));
                    history_protected = FALSE;
                    return;
                }

                // may be added in a the state's region rather than the state
                StateCanvas * c = new StateCanvas(b, the_canvas(), scenePoint.x(), scenePoint.y());

                c->show();
                c->upper();
                canvas()->update();
                StateCanvas::force_inside(c, TRUE);
                canvas()->update();
                history_protected = FALSE;
                window()->package_modified();
                return; // canvas already updated
            }
        }
        break;

        case UmlRegion: {
            history_protected = TRUE;
            unselect_all();
            window()->selectOn();
            history_save();

            QGraphicsItem * ci = the_canvas()->collision(scenePoint.toPoint());
            DiagramItem * di;

            if ((ci != 0) &&
                ((di = QCanvasItemToDiagramItem(ci)) != 0) &&
                (di->typeUmlCode() == UmlState) &&
                ((BrowserState *)((StateCanvas *) di)->get_bn())->may_contains(action)) {
                BrowserRegion::add_region(((StateCanvas *) di)->get_bn());
                window()->package_modified();
            }
        }
        break;

        case InitialPS:
        case EntryPointPS:
        case FinalPS:
        case TerminatePS:
        case ExitPointPS:
        case DeepHistoryPS:
        case ShallowHistoryPS:
        case JunctionPS:
        case ChoicePS:
        case ForkPS:
        case JoinPS: {
            history_protected = TRUE;
            unselect_all();
            window()->selectOn();
            history_save();

            QGraphicsItem * ci = the_canvas()->collision(scenePoint.toPoint());
            DiagramItem * di;
            bool specified = ((ci != 0) &&
                              ((di = QCanvasItemToDiagramItem(ci)) != 0) &&
                              (di->typeUmlCode() == UmlState) &&
                              ((BrowserState *)((StateCanvas *) di)->get_bn())->may_contains(action));
            BrowserNode * parent;

            if (specified) {
                if ((parent = ((StateCanvas *) di)->pointed_region(scenePoint.toPoint())) == 0)
                    parent = ((StateCanvas *) di)->get_bn();
            }
            else
                parent = (BrowserNode *) window()->browser_diagram()->parent();

            BrowserNode * b = BrowserPseudoState::get_pseudostate(parent, action);

            if (b != 0) {
                PseudoStateCanvas * c =
                    // may be added in a the state's region rather than the state
                    new PseudoStateCanvas(b, the_canvas(), scenePoint.x(), scenePoint.y());

                c->show();
                c->upper();
                StateCanvas::force_inside(c, FALSE);
                window()->package_modified();
            }
        }
        break;

        case UmlStateAction:
        case UmlSignalIn:
        case UmlSignalOut: {
            history_protected = TRUE;
            unselect_all();
            window()->selectOn();
            history_save();

            QGraphicsItem * ci = the_canvas()->collision(scenePoint.toPoint());
            DiagramItem * di;
            bool specified = ((ci != 0) &&
                              ((di = QCanvasItemToDiagramItem(ci)) != 0) &&
                              (di->typeUmlCode() == UmlState) &&
                              ((BrowserState *)((StateCanvas *) di)->get_bn())->may_contains(UmlStateAction));
            BrowserNode * parent;

            if (specified) {
                if ((parent = ((StateCanvas *) di)->pointed_region(scenePoint.toPoint())) == 0)
                    parent = ((StateCanvas *) di)->get_bn();
            }
            else
                parent = (BrowserNode *) window()->browser_diagram()->parent();

            BrowserNode * b = BrowserStateAction::add_stateaction(parent);

            switch (action) {
            case UmlSignalIn:
                ((StateActionData *) b->get_data())->set_stereotype("receive-signal");
                break;

            case UmlSignalOut:
                ((StateActionData *) b->get_data())->set_stereotype("send-signal");
                break;

            default:	// to avoid warning
                break;
            }

            StateActionCanvas * c =
                // may be added in a the state's region rather than the state
                new StateActionCanvas(b, the_canvas(), scenePoint.x(), scenePoint.y());

            c->show();
            c->upper();
            StateCanvas::force_inside(c, FALSE);
            window()->package_modified();
        }
        break;

        default:
            DiagramView::mousePressEvent(e);
            return;
        }

        canvas()->update();
        history_protected = FALSE;
    }
    else
        DiagramView::mousePressEvent(e);
}