QSize PianoKeybd::sizeHint() const { return mapFromScene(sceneRect()).boundingRect().size(); }
void DiagramDrawItem::setPos2(qreal x,qreal y) { myPos2=mapFromScene(QPointF(x,y)); myPolygon=createPath(); setPolygon(myPolygon); }
GfxNoteItem *Item::createGfxNote(QPointF p0) { ASSERT(d); QPointF p1 = mapFromScene(DragLine::drag(scene(), mapToScene(p0), style())); return newGfxNote(p0, p1); }
void DrawingPolyItem::setPointPos(int index, const QPointF& scenePos) { resizeItem(point(index), mapToParent(mapFromScene(scenePos))); }
bool IMEView::sceneEvent(QEvent* event) { switch (event->type()) { case QEvent::GestureOverride: { // consume all gestures if we are handling touches QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = 0; if ((g = ge->gesture(Qt::TapGesture))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } else if ((g = ge->gesture(Qt::TapAndHoldGesture))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } else if ((g = ge->gesture(Qt::PinchGesture))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } else if ((g = ge->gesture((Qt::GestureType) SysMgrGestureFlick))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } else if ((g = ge->gesture((Qt::GestureType) SysMgrGestureSingleClick))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } else if ((g = ge->gesture((Qt::GestureType) SysMgrGestureSingleClick))) { if (acceptPoint(mapFromScene(ge->mapToGraphicsScene(g->hotSpot())))) { event->accept(); return true; } } } break; case QEvent::Gesture: { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g && g->state() == Qt::GestureFinished) { tapEvent(static_cast<QTapGesture*>(g)); return true; } if (!g) { QGesture* g = ge->gesture((Qt::GestureType) SysMgrGestureScreenEdgeFlick); if (g && g->state() == Qt::GestureFinished) { screenEdgeFlickEvent(static_cast<ScreenEdgeFlickGesture*>(g)); return true; } } } break; case QEvent::TouchBegin: touchBegin(static_cast<QTouchEvent*>(event)); return event->isAccepted(); case QEvent::TouchUpdate: touchUpdate(static_cast<QTouchEvent*>(event)); return event->isAccepted(); case QEvent::TouchEnd: touchEnd(static_cast<QTouchEvent*>(event)); return event->isAccepted(); default: break; } return QGraphicsObject::sceneEvent(event); }
/*! \reimp */ void HbRatingSlider::gestureEvent(QGestureEvent *event) { Q_D (HbRatingSlider); if(event->gesture(Qt::TapGesture)) { HbTapGesture *tap = qobject_cast<HbTapGesture *>(event->gesture(Qt::TapGesture)); switch(tap->state()) { case Qt::GestureStarted: { qreal xVal = mapFromScene(event->mapToGraphicsScene(tap->position( ))).x(); int rating = d->calculateProgressValue(xVal); if(rating == -1) { return; } if(d->mReadOnly) { event->ignore(); return; } QRectF rect = d->mTouchArea->boundingRect(); if(rect.contains(xVal,0 )) { HbWidgetFeedback::triggered(this, Hb::InstantPressed); d->mMousePressed = true; updatePrimitives(); rating = d->calculateProgressValue(xVal); setCurrentRating(rating); event->accept(); } else { event->ignore(); } } break; case Qt::GestureFinished: // Reset state { qreal xVal = mapFromScene(event->mapToGraphicsScene(tap->position( ))).x(); QRectF rect = d->mTouchArea->boundingRect(); int rating=0; if(rect.contains(xVal,0 )) { if(d->mReadOnly) { event->ignore(); return; } if(!d->mMousePressed){ return; } if(xVal <0) { setCurrentRating(0); emit ratingDone (d->mCurrentValue); return; } rating = d->calculateProgressValue(xVal); if(!toolTip().isNull()) { HbToolTip::showText(toolTip(),this); } setCurrentRating(rating); HbWidgetFeedback::triggered(this, Hb::InstantReleased); if(d->mCurrentValue) { emit ratingDone (d->mCurrentValue); } event->accept(); d->mMousePressed = false; updatePrimitives(); } else { d->mMousePressed = false; updatePrimitives(); if(xVal <rect.x() ) { setCurrentRating(0); emit ratingDone (d->mCurrentValue); } } } break; default: break; } }else if(event->gesture(Qt::PanGesture)) { HbPanGesture *pan = qobject_cast<HbPanGesture *>(event->gesture(Qt::PanGesture)); switch(pan->state()) { case Qt::GestureUpdated: { if(!d->mMousePressed) { return; } qreal xVal = mapFromScene(event->mapToGraphicsScene( pan->startPos()+pan->offset())).x(); QRectF rect = d->mTouchArea->boundingRect(); int rating=0; if(rect.contains(xVal,0 )) { if(d->mReadOnly) { event->ignore(); return; } if(xVal <0) { setCurrentRating(0); return; } rating = d->calculateProgressValue(xVal); if(!toolTip().isNull()) { HbToolTip::showText(toolTip(),this); } setCurrentRating(rating); HbWidgetFeedback::continuousTriggered(this, Hb::ContinuousDragged); emit ratingChanged (d->mCurrentValue); event->accept(); } else { setCurrentRating(0); } } break; case Qt::GestureFinished: // Reset state { qreal xVal = mapFromScene(event->mapToGraphicsScene( pan->startPos()+pan->offset())).x(); QRectF rect = d->mTouchArea->boundingRect(); d->mMousePressed = false; updatePrimitives(); int rating=0; if(rect.contains(xVal,0 )) { if(d->mReadOnly) { event->ignore(); return; } } if(xVal <0) { setCurrentRating(0); emit ratingDone (d->mCurrentValue); return; } rating = d->calculateProgressValue(xVal); setCurrentRating(rating); HbWidgetFeedback::triggered(this, Hb::InstantReleased); if(d->mCurrentValue) { emit ratingDone (d->mCurrentValue); } event->accept(); } default: break; } } }
void ExploreLiveView::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget * widget) { if(!isReady) return; prePaint(painter); postPaint(painter); auto glwidget = (Viewer*)widget; if (glwidget && meshes.size()) { QRectF parentRect = parentItem()->sceneBoundingRect(); if (isCacheImage && cachedImage.isNull()) { QOpenGLContext context; context.setShareContext(glwidget->context()); context.setFormat(glwidget->format()); context.create(); QOffscreenSurface m_offscreenSurface; m_offscreenSurface.setFormat(context.format()); m_offscreenSurface.create(); context.makeCurrent(&m_offscreenSurface); QOpenGLFramebufferObjectFormat fboformat; fboformat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); QOpenGLFramebufferObject renderFbo(cacheImageSize*1.5, cacheImageSize, fboformat); renderFbo.bind(); glwidget->glEnable(GL_DEPTH_TEST); glwidget->glEnable(GL_BLEND); glwidget->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glwidget->glCullFace(GL_BACK); glwidget->glClearColor(0,0,0,0); glwidget->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glwidget->glViewport(0, 0, cacheImageSize*1.5, cacheImageSize); // XXX Fix // glwidget->glPointSize(10); // Draw aux meshes for (auto mesh : meshes) { if (mesh.isPoints) glwidget->drawOrientedPoints(mesh.points, mesh.normals, mesh.color, glwidget->pvm); else glwidget->drawTriangles(mesh.color, mesh.points, mesh.normals, glwidget->pvm); } glwidget->glDisable(GL_DEPTH_TEST); glwidget->glFlush(); renderFbo.release(); cachedImage = renderFbo.toImage(); isReady = true; // Thanks for sharing! glwidget->makeCurrent(); } // Draw as image if(isCacheImage) { int w = shapeRect.width(); painter->drawImage(w * -0.5, w * -0.5, cachedImage.scaledToWidth(w)); } if(!isCacheImage) { auto r = shapeRect; // scale view double s = 1.5; r.setWidth(r.width() * s); r.setHeight(r.height() * s); r.moveCenter(this->mapToScene(boundingRect().center())); painter->beginNativePainting(); auto v = scene()->views().first(); QPoint viewDelta = v->mapFromScene(r.topLeft()); if (viewDelta.manhattanLength() > 5) r.moveTopLeft(viewDelta); auto camera = ExploreProcess::defaultCamera(document->extent().length()); glwidget->eyePos = camera.first; glwidget->pvm = camera.second; glwidget->glViewport(r.left(), v->height() - r.height() - r.top(), r.width(), r.height()); // Clipping OpenGL glwidget->glEnable(GL_SCISSOR_TEST); glwidget->glScissor(parentRect.x(), v->height() - parentRect.height() - parentRect.top(), parentRect.width(), parentRect.height()); glwidget->glClear(GL_DEPTH_BUFFER_BIT); // FIX XXX // glwidget->glPointSize(2); // Draw aux meshes for (auto mesh : meshes) { if (mesh.isPoints) glwidget->drawOrientedPoints(mesh.points, mesh.normals, mesh.color, glwidget->pvm); else glwidget->drawTriangles(mesh.color, mesh.points, mesh.normals, glwidget->pvm); } glwidget->glDisable(GL_SCISSOR_TEST); painter->endNativePainting(); } } }
bool QgsComposerNodesItem::addNode( QPointF pt, const bool checkArea, const double radius ) { const QPointF start = mapFromScene( pt ); double minDistance = std::numeric_limits<double>::max(); double maxDistance = ( checkArea ) ? radius : minDistance; bool rc = false; int idx = -1; for ( int i = 0; i != mPolygon.size(); i++ ) { // get nodes of polyline const QPointF pt1 = mPolygon.at( i ); QPointF pt2 = mPolygon.first(); if (( i + 1 ) != mPolygon.size() ) pt2 = mPolygon.at( i + 1 ); // compute line eq const double coef = ( pt2.y() - pt1.y() ) / ( pt2.x() - pt1.x() ); const double b = pt1.y() - coef * pt1.x(); double distance = std::numeric_limits<double>::max(); if ( qIsInf( coef ) ) distance = qAbs( pt1.x() - start.x() ); else { const double coef2 = ( -1 / coef ); const double b2 = start.y() - coef2 * start.x(); QPointF inter; if ( qIsInf( coef2 ) ) { distance = qAbs( pt1.y() - start.y() ); inter.setX( start.x() ); inter.setY( pt1.y() ); } else { const double interx = ( b - b2 ) / ( coef2 - coef ); const double intery = interx * coef2 + b2; inter.setX( interx ); inter.setY( intery ); } // check if intersection is within the line const double length1 = computeDistance( inter, pt1 ); const double length2 = computeDistance( inter, pt2 ); const double length3 = computeDistance( pt1, pt2 ); const double length4 = length1 + length2; if ( qAbs( length3 - length4 ) < std::numeric_limits<float>::epsilon() ) distance = computeDistance( inter, start ); } if ( distance < minDistance && distance < maxDistance ) { minDistance = distance; idx = i; } } if ( idx >= 0 ) { rc = _addNode( idx, start, maxDistance ); updateSceneRect(); } return rc; }
void PianoView::wheelEvent(QWheelEvent* event) { int step = event->delta() / 120; double xmag = transform().m11(); double ymag = transform().m22(); if (event->modifiers() == Qt::ControlModifier) { if (step > 0) { for (int i = 0; i < step; ++i) { if (xmag > 10.0) break; scale(1.1, 1.0); xmag *= 1.1; } } else { for (int i = 0; i < -step; ++i) { if (xmag < 0.001) break; scale(.9, 1.0); xmag *= .9; } } emit magChanged(xmag, ymag); int tpix = (480 * 4) * xmag; magStep = -5; if (tpix <= 4000) magStep = -4; if (tpix <= 2000) magStep = -3; if (tpix <= 1000) magStep = -2; if (tpix <= 500) magStep = -1; if (tpix <= 128) magStep = 0; if (tpix <= 64) magStep = 1; if (tpix <= 32) magStep = 2; if (tpix <= 16) magStep = 3; if (tpix <= 8) magStep = 4; if (tpix <= 4) magStep = 5; if (tpix <= 2) magStep = 6; // // if xpos <= 0, then the scene is centered // there is no scroll bar anymore sending // change signals, so we have to do it here: // double xpos = -(mapFromScene(QPointF()).x()); if (xpos <= 0) emit xposChanged(xpos); } else if (event->modifiers() == Qt::ShiftModifier) { QWheelEvent we(event->pos(), event->delta(), event->buttons(), 0, Qt::Horizontal); QGraphicsView::wheelEvent(&we); } else if (event->modifiers() == 0) { QGraphicsView::wheelEvent(event); } else if (event->modifiers() == (Qt::ShiftModifier | Qt::ControlModifier)) { if (step > 0) { for (int i = 0; i < step; ++i) { if (ymag > 3.0) break; scale(1.0, 1.1); ymag *= 1.1; } } else { for (int i = 0; i < -step; ++i) { if (ymag < 0.4) break; scale(1.0, .9); ymag *= .9; } } emit magChanged(xmag, ymag); } }
bool NodeBackDrop::isNearbyResizeHandle(const QPointF& scenePos) { QPointF p = mapFromScene(scenePos); QPolygonF resizePoly = _imp->resizeHandle->polygon(); return resizePoly.containsPoint(p,Qt::OddEvenFill); }
QRectF Snake::boundingRect() const { qreal minX = head.x(); qreal minY = head.y(); qreal maxX = head.x(); qreal maxY = head.y(); foreach (QPointF p, tail) { maxX = p.x() > maxX ? p.x() : maxX; maxY = p.y() > maxY ? p.y() : maxY; minX = p.x() < minX ? p.x() : minX; minY = p.y() < minY ? p.y() : minY; } QPointF tl = mapFromScene(QPointF(minX, minY)); QPointF br = mapFromScene(QPointF(maxX, maxY)); QRectF bound = QRectF(tl.x(), // x tl.y(), // y br.x() - tl.x() + SNAKE_SIZE, // width br.y() - tl.y() + SNAKE_SIZE //height ); return bound; } QPainterPath Snake::shape() const { QPainterPath path; path.setFillRule(Qt::WindingFill);
bool NodeBackDrop::isNearbyHeader(const QPointF& scenePos) { QPointF p = mapFromScene(scenePos); QRectF headerBbox = _imp->header->boundingRect(); headerBbox.adjust(-5, -5, 5, 5); return headerBbox.contains(p); }
void GameView::resizeRubberBand(const QPointF &cursorPoint) { if (rubberBand) rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized()); }
void GameView::startRubberBand(const QPointF &_selectionOrigin) { selectionOrigin = _selectionOrigin; rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); rubberBand->show(); }
void QDeclarativePinchArea::updatePinch() { Q_D(QDeclarativePinchArea); if (d->touchPoints.count() == 0) { if (d->inPinch) { d->stealMouse = false; setKeepMouseGrab(false); d->inPinch = false; QPointF pinchCenter = mapFromScene(d->sceneLastCenter); QDeclarativePinchEvent pe(pinchCenter, d->pinchLastScale, d->pinchLastAngle, d->pinchRotation); pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(pinchCenter); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(mapFromScene(d->lastPoint1)); pe.setPoint2(mapFromScene(d->lastPoint2)); emit pinchFinished(&pe); d->pinchStartDist = 0; d->pinchActivated = false; if (d->pinch && d->pinch->target()) d->pinch->setActive(false); } return; } QTouchEvent::TouchPoint touchPoint1 = d->touchPoints.at(0); QTouchEvent::TouchPoint touchPoint2 = d->touchPoints.at(d->touchPoints. count() >= 2 ? 1 : 0); if (d->touchPoints.count() == 2 && (touchPoint1.state() & Qt::TouchPointPressed || touchPoint2.state() & Qt::TouchPointPressed)) { d->id1 = touchPoint1.id(); d->sceneStartPoint1 = touchPoint1.scenePos(); d->sceneStartPoint2 = touchPoint2.scenePos(); d->inPinch = false; d->pinchRejected = false; d->pinchActivated = true; } else if (d->pinchActivated && !d->pinchRejected) { const int dragThreshold = QApplication::startDragDistance(); QPointF p1 = touchPoint1.scenePos(); QPointF p2 = touchPoint2.scenePos(); qreal dx = p1.x() - p2.x(); qreal dy = p1.y() - p2.y(); qreal dist = sqrt(dx*dx + dy*dy); QPointF sceneCenter = (p1 + p2)/2; qreal angle = QLineF(p1, p2).angle(); if (d->touchPoints.count() == 1) { // If we only have one point then just move the center if (d->id1 == touchPoint1.id()) sceneCenter = d->sceneLastCenter + touchPoint1.scenePos() - d->lastPoint1; else sceneCenter = d->sceneLastCenter + touchPoint2.scenePos() - d->lastPoint2; angle = d->pinchLastAngle; } d->id1 = touchPoint1.id(); if (angle > 180) angle -= 360; if (!d->inPinch) { if (d->touchPoints.count() >= 2 && (qAbs(p1.x()-d->sceneStartPoint1.x()) > dragThreshold || qAbs(p1.y()-d->sceneStartPoint1.y()) > dragThreshold || qAbs(p2.x()-d->sceneStartPoint2.x()) > dragThreshold || qAbs(p2.y()-d->sceneStartPoint2.y()) > dragThreshold)) { d->sceneStartCenter = sceneCenter; d->sceneLastCenter = sceneCenter; d->pinchStartCenter = mapFromScene(sceneCenter); d->pinchStartDist = dist; d->pinchStartAngle = angle; d->pinchLastScale = 1.0; d->pinchLastAngle = angle; d->pinchRotation = 0.0; d->lastPoint1 = p1; d->lastPoint2 = p2; QDeclarativePinchEvent pe(d->pinchStartCenter, 1.0, angle, 0.0); pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(d->pinchStartCenter); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(mapFromScene(d->lastPoint1)); pe.setPoint2(mapFromScene(d->lastPoint2)); pe.setPointCount(d->touchPoints.count()); emit pinchStarted(&pe); if (pe.accepted()) { d->inPinch = true; d->stealMouse = true; QGraphicsScene *s = scene(); if (s && s->mouseGrabberItem() != this) grabMouse(); setKeepMouseGrab(true); if (d->pinch && d->pinch->target()) { d->pinchStartPos = pinch()->target()->pos(); d->pinchStartScale = d->pinch->target()->scale(); d->pinchStartRotation = d->pinch->target()->rotation(); d->pinch->setActive(true); } } else { d->pinchRejected = true; } } } else if (d->pinchStartDist > 0) { qreal scale = dist ? dist / d->pinchStartDist : d->pinchLastScale; qreal da = d->pinchLastAngle - angle; if (da > 180) da -= 360; else if (da < -180) da += 360; d->pinchRotation += da; QPointF pinchCenter = mapFromScene(sceneCenter); QDeclarativePinchEvent pe(pinchCenter, scale, angle, d->pinchRotation); pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(mapFromScene(d->sceneLastCenter)); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(touchPoint1.pos()); pe.setPoint2(touchPoint2.pos()); pe.setPointCount(d->touchPoints.count()); d->pinchLastScale = scale; d->sceneLastCenter = sceneCenter; d->pinchLastAngle = angle; d->lastPoint1 = touchPoint1.scenePos(); d->lastPoint2 = touchPoint2.scenePos(); emit pinchUpdated(&pe); if (d->pinch && d->pinch->target()) { qreal s = d->pinchStartScale * scale; s = qMin(qMax(pinch()->minimumScale(),s), pinch()->maximumScale()); pinch()->target()->setScale(s); QPointF pos = sceneCenter - d->sceneStartCenter + d->pinchStartPos; if (pinch()->axis() & QDeclarativePinch::XAxis) { qreal x = pos.x(); if (x < pinch()->xmin()) x = pinch()->xmin(); else if (x > pinch()->xmax()) x = pinch()->xmax(); pinch()->target()->setX(x); } if (pinch()->axis() & QDeclarativePinch::YAxis) { qreal y = pos.y(); if (y < pinch()->ymin()) y = pinch()->ymin(); else if (y > pinch()->ymax()) y = pinch()->ymax(); pinch()->target()->setY(y); } if (d->pinchStartRotation >= pinch()->minimumRotation() && d->pinchStartRotation <= pinch()->maximumRotation()) { qreal r = d->pinchRotation + d->pinchStartRotation; r = qMin(qMax(pinch()->minimumRotation(),r), pinch()->maximumRotation()); pinch()->target()->setRotation(r); } } } } }
void EllipseTextureGraphicsItem::_doDrawOutput(QPainter* painter) { Q_UNUSED(painter); // Get input and output ellipses. std::tr1::shared_ptr<Ellipse> inputEllipse = std::tr1::static_pointer_cast<Ellipse>(_inputShape); std::tr1::shared_ptr<Ellipse> outputEllipse = std::tr1::static_pointer_cast<Ellipse>(_shape); // Start / end angle. //const float startAngle = 0; //const float endAngle = 2*M_PI; // //float angle; QPointF currentInputPoint; QPointF prevInputPoint(0, 0); QPointF currentOutputPoint; QPointF prevOutputPoint(0, 0); // Input ellipse parameters. const QPointF& inputCenter = inputEllipse->getCenter(); const QPointF& inputControlCenter = inputEllipse->getVertex(4); float inputHorizRadius = inputEllipse->getHorizontalRadius(); float inputVertRadius = inputEllipse->getVerticalRadius(); float inputRotation = inputEllipse->getRotationRadians(); // Output ellipse parameters. const QPointF& outputCenter = mapFromScene(outputEllipse->getCenter()); const QPointF& outputControlCenter = mapFromScene(outputEllipse->getVertex(4)); float outputHorizRadius = outputEllipse->getHorizontalRadius(); float outputVertRadius = outputEllipse->getVerticalRadius(); float outputRotation = outputEllipse->getRotationRadians(); // Variation in angle at each step of the loop. const int N_TRIANGLES = 100; const float ANGLE_STEP = 2*M_PI/N_TRIANGLES; float circleAngle = 0; for (int i=0; i<=N_TRIANGLES; i++, circleAngle += ANGLE_STEP) { // Set next (current) points. _setPointOfEllipseAtAngle(currentInputPoint, inputCenter, inputHorizRadius, inputVertRadius, inputRotation, circleAngle); _setPointOfEllipseAtAngle(currentOutputPoint, outputCenter, outputHorizRadius, outputVertRadius, outputRotation, circleAngle); // We don't draw the first point. if (i > 0) { // Draw triangle. glBegin(GL_TRIANGLES); Util::setGlTexPoint(*_texture, inputControlCenter, outputControlCenter); Util::setGlTexPoint(*_texture, prevInputPoint, prevOutputPoint); Util::setGlTexPoint(*_texture, currentInputPoint, currentOutputPoint); glEnd(); } // Save point for next iteration. prevInputPoint.setX(currentInputPoint.x()); prevInputPoint.setY(currentInputPoint.y()); prevOutputPoint.setX(currentOutputPoint.x()); prevOutputPoint.setY(currentOutputPoint.y()); } }
QRect ImageView::sceneToViewport(const QRectF &rect) const { QPoint topLeft = mapFromScene(rect.topLeft()); QPoint bottomRight = mapFromScene(rect.bottomRight()); return QRect(topLeft, bottomRight); }
void AbstractGraphicsRectItem::updateBottomRight(const QPointF &newPos) { QRectF r = rect(); r.setBottomRight(mapFromScene(newPos)); updateRect(r); }
void QgsComposerMouseHandles::drawSelectedItemBounds( QPainter* painter ) { //draw dotted border around selected items to give visual feedback which items are selected QList<QgsComposerItem*> selectedItems = mComposition->selectedComposerItems( false ); if ( selectedItems.size() == 0 ) { return; } //use difference mode so that they are visible regardless of item colors painter->save(); painter->setCompositionMode( QPainter::CompositionMode_Difference ); // use a grey dashed pen - in difference mode this should always be visible QPen selectedItemPen = QPen( QColor( 144, 144, 144, 255 ) ); selectedItemPen.setStyle( Qt::DashLine ); selectedItemPen.setWidth( 0 ); painter->setPen( selectedItemPen ); painter->setBrush( Qt::NoBrush ); QList<QgsComposerItem*>::iterator itemIter = selectedItems.begin(); for ( ; itemIter != selectedItems.end(); ++itemIter ) { //get bounds of selected item QPolygonF itemBounds; if ( mIsDragging && !( *itemIter )->positionLock() ) { //if currently dragging, draw selected item bounds relative to current mouse position //first, get bounds of current item in scene coordinates QPolygonF itemSceneBounds = ( *itemIter )->mapToScene(( *itemIter )->rectWithFrame() ); //now, translate it by the current movement amount //IMPORTANT - this is done in scene coordinates, since we don't want any rotation/non-translation transforms to affect the movement itemSceneBounds.translate( transform().dx(), transform().dy() ); //finally, remap it to the mouse handle item's coordinate system so it's ready for drawing itemBounds = mapFromScene( itemSceneBounds ); } else if ( mIsResizing && !( *itemIter )->positionLock() ) { //if currently resizing, calculate relative resize of this item if ( selectedItems.size() > 1 ) { //get item bounds in mouse handle item's coordinate system QRectF itemRect = mapRectFromItem(( *itemIter ), ( *itemIter )->rectWithFrame() ); //now, resize it relative to the current resized dimensions of the mouse handles QgsComposerUtils::relativeResizeRect( itemRect, QRectF( -mResizeMoveX, -mResizeMoveY, mBeginHandleWidth, mBeginHandleHeight ), mResizeRect ); itemBounds = QPolygonF( itemRect ); } else { //single item selected itemBounds = rect(); } } else { //not resizing or moving, so just map from scene bounds itemBounds = mapRectFromItem(( *itemIter ), ( *itemIter )->rectWithFrame() ); } painter->drawPolygon( itemBounds ); } painter->restore(); }
void SPoint::setPosition(QPointF point) { position=mapFromScene(point); }
void PolygonObject::updateRubber(QPainter* painter) { int rubberMode = objectRubberMode(); if(rubberMode == OBJ_RUBBER_POLYGON) { setObjectPos(objectRubberPoint("POLYGON_POINT_0")); bool ok = false; QString numStr = objectRubberText("POLYGON_NUM_POINTS"); if(numStr.isNull()) return; int num = numStr.toInt(&ok); if(!ok) return; QString appendStr; QPainterPath rubberPath; rubberPath.moveTo(mapFromScene(objectRubberPoint("POLYGON_POINT_0"))); for(int i = 1; i <= num; i++) { appendStr = "POLYGON_POINT_" + QString().setNum(i); QPointF appendPoint = mapFromScene(objectRubberPoint(appendStr)); rubberPath.lineTo(appendPoint); } //rubberPath.lineTo(0,0); updatePath(rubberPath); //Ensure the path isn't updated until the number of points is changed again setObjectRubberText("POLYGON_NUM_POINTS", QString()); } else if(rubberMode == OBJ_RUBBER_POLYGON_INSCRIBE) { setObjectPos(objectRubberPoint("POLYGON_CENTER")); quint16 numSides = objectRubberPoint("POLYGON_NUM_SIDES").x(); QPointF inscribePoint = mapFromScene(objectRubberPoint("POLYGON_INSCRIBE_POINT")); QLineF inscribeLine = QLineF(QPointF(0,0), inscribePoint); qreal inscribeAngle = inscribeLine.angle(); qreal inscribeInc = 360.0/numSides; if(painter) drawRubberLine(inscribeLine, painter, VIEW_COLOR_CROSSHAIR); QPainterPath inscribePath; //First Point inscribePath.moveTo(inscribePoint); //Remaining Points for(int i = 1; i < numSides; i++) { inscribeLine.setAngle(inscribeAngle + inscribeInc*i); inscribePath.lineTo(inscribeLine.p2()); } updatePath(inscribePath); } else if(rubberMode == OBJ_RUBBER_POLYGON_CIRCUMSCRIBE) { setObjectPos(objectRubberPoint("POLYGON_CENTER")); quint16 numSides = objectRubberPoint("POLYGON_NUM_SIDES").x(); QPointF circumscribePoint = mapFromScene(objectRubberPoint("POLYGON_CIRCUMSCRIBE_POINT")); QLineF circumscribeLine = QLineF(QPointF(0,0), circumscribePoint); qreal circumscribeAngle = circumscribeLine.angle(); qreal circumscribeInc = 360.0/numSides; if(painter) drawRubberLine(circumscribeLine, painter, VIEW_COLOR_CROSSHAIR); QPainterPath circumscribePath; //First Point QLineF prev(circumscribeLine.p2(), QPointF(0,0)); prev = prev.normalVector(); circumscribeLine.setAngle(circumscribeAngle + circumscribeInc); QLineF perp(circumscribeLine.p2(), QPointF(0,0)); perp = perp.normalVector(); QPointF iPoint; perp.intersect(prev, &iPoint); circumscribePath.moveTo(iPoint); //Remaining Points for(int i = 2; i <= numSides; i++) { prev = perp; circumscribeLine.setAngle(circumscribeAngle + circumscribeInc*i); perp = QLineF(circumscribeLine.p2(), QPointF(0,0)); perp = perp.normalVector(); perp.intersect(prev, &iPoint); circumscribePath.lineTo(iPoint); } updatePath(circumscribePath); } else if(rubberMode == OBJ_RUBBER_GRIP) { if(painter) { int elemCount = normalPath.elementCount(); QPointF gripPoint = objectRubberPoint("GRIP_POINT"); if(gripIndex == -1) gripIndex = findIndex(gripPoint); if(gripIndex == -1) return; int m = 0; int n = 0; if(!gripIndex) { m = elemCount-1; n = 1; } else if(gripIndex == elemCount-1) { m = elemCount-2; n = 0; } else { m = gripIndex-1; n = gripIndex+1; } QPainterPath::Element em = normalPath.elementAt(m); QPainterPath::Element en = normalPath.elementAt(n); QPointF emPoint = QPointF(em.x, em.y); QPointF enPoint = QPointF(en.x, en.y); painter->drawLine(emPoint, mapFromScene(objectRubberPoint(QString()))); painter->drawLine(enPoint, mapFromScene(objectRubberPoint(QString()))); QLineF rubLine(mapFromScene(gripPoint), mapFromScene(objectRubberPoint(QString()))); drawRubberLine(rubLine, painter, VIEW_COLOR_CROSSHAIR); } } }
void CircleObject::updateRubber(QPainter* painter) { int rubberMode = objectRubberMode(); if(rubberMode == OBJ_RUBBER_CIRCLE_1P_RAD) { QPointF sceneCenterPoint = objectRubberPoint("CIRCLE_CENTER"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_RADIUS"); QPointF itemCenterPoint = mapFromScene(sceneCenterPoint); QPointF itemQSnapPoint = mapFromScene(sceneQSnapPoint); QLineF itemLine(itemCenterPoint, itemQSnapPoint); setObjectCenter(sceneCenterPoint); QLineF sceneLine(sceneCenterPoint, sceneQSnapPoint); qreal radius = sceneLine.length(); setObjectRadius(radius); if(painter) drawRubberLine(itemLine, painter, VIEW_COLOR_CROSSHAIR); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_1P_DIA) { QPointF sceneCenterPoint = objectRubberPoint("CIRCLE_CENTER"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_DIAMETER"); QPointF itemCenterPoint = mapFromScene(sceneCenterPoint); QPointF itemQSnapPoint = mapFromScene(sceneQSnapPoint); QLineF itemLine(itemCenterPoint, itemQSnapPoint); setObjectCenter(sceneCenterPoint); QLineF sceneLine(sceneCenterPoint, sceneQSnapPoint); qreal diameter = sceneLine.length(); setObjectDiameter(diameter); if(painter) drawRubberLine(itemLine, painter, VIEW_COLOR_CROSSHAIR); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_2P) { QPointF sceneTan1Point = objectRubberPoint("CIRCLE_TAN1"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_TAN2"); QLineF sceneLine(sceneTan1Point, sceneQSnapPoint); setObjectCenter(sceneLine.pointAt(0.5)); qreal diameter = sceneLine.length(); setObjectDiameter(diameter); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_3P) { QPointF sceneTan1Point = objectRubberPoint("CIRCLE_TAN1"); QPointF sceneTan2Point = objectRubberPoint("CIRCLE_TAN2"); QPointF sceneTan3Point = objectRubberPoint("CIRCLE_TAN3"); double sceneCenterX; double sceneCenterY; getArcCenter(sceneTan1Point.x(), sceneTan1Point.y(), sceneTan2Point.x(), sceneTan2Point.y(), sceneTan3Point.x(), sceneTan3Point.y(), &sceneCenterX, &sceneCenterY); QPointF sceneCenterPoint(sceneCenterX, sceneCenterY); QLineF sceneLine(sceneCenterPoint, sceneTan3Point); setObjectCenter(sceneCenterPoint); qreal radius = sceneLine.length(); setObjectRadius(radius); updatePath(); } else if(rubberMode == OBJ_RUBBER_GRIP) { if(painter) { QPointF gripPoint = objectRubberPoint("GRIP_POINT"); if(gripPoint == objectCenter()) { painter->drawEllipse(rect().translated(mapFromScene(objectRubberPoint(QString()))-mapFromScene(gripPoint))); } else { qreal gripRadius = QLineF(objectCenter(), objectRubberPoint(QString())).length(); painter->drawEllipse(QPointF(), gripRadius, gripRadius); } QLineF rubLine(mapFromScene(gripPoint), mapFromScene(objectRubberPoint(QString()))); drawRubberLine(rubLine, painter, VIEW_COLOR_CROSSHAIR); } } }
//virtual bool AlphabetPage::tapAndHoldGesture(QTapAndHoldGesture *tapHoldEvent,QGestureEvent * baseGestureEvent) { // qDebug() << __PRETTY_FUNCTION__ << ": Tap-N-Hold Gesture"; //if nothing is tracking, reject int mainTouchId; if (!anyTouchTracking(&mainTouchId)) { qDebug() << __PRETTY_FUNCTION__ << ": Rejected; touch FSM reports no touchId is currently tracked"; return true; } //TODO: MULTI-TOUCH: here is where I can get into deep trouble; I've just assumed that the main touch point is part of this gesture. It need not be if (!okToUseTapAndHold(mainTouchId)) { qDebug() << __PRETTY_FUNCTION__ << ": Rejected; a previous gesture has already claimed touch id " << mainTouchId; return true; } AlphabetIconLayout * pAlphaLayout = qobject_cast<AlphabetIconLayout *>(m_qp_iconLayout); if (!pAlphaLayout) { qDebug() << __PRETTY_FUNCTION__ << ": Rejected; There doesn't seem to be a layout on this page (or it isn't an Alpha layout)"; return true; } //if I'm not in reorder mode, then flip to it now; this is just going to change all the graphics in the icons // and enable them to sense taps on special, decorator areas setPageMode(PageMode::Reorder); //note calling this when already in Reorder mode does nothing, so it's ok to just call it and avoid the "if" QPointF positionOfTapICS = mapFromScene(baseGestureEvent->mapToGraphicsScene(tapHoldEvent->hotSpot())); // qDebug() << "tap-n-hold position from the event: " << positionOfTapICS; //TODO: TEMP: the tap coordinate is in PAGE ICS...the layout ICS is a little bit different. It needs to be mapped for total correctness // for now, this will work QPointF positionOfTapLayoutCS = layoutCoordinateFromPageCoordinate(positionOfTapICS); //first, it there is an icon already in motion, silently consume event (yum!) if (m_qp_cached_trackingIcon) { qDebug() << __PRETTY_FUNCTION__ << ": Rejected; Already tracking an icon"; return true; } //tell the layout to start tracking an icon at the position given if (!pAlphaLayout->startTrackingIcon(positionOfTapLayoutCS,m_trackingIconUids)) { qDebug() << __PRETTY_FUNCTION__ << ": Rejected; No icon found at tap-n-hold coordinate " << positionOfTapLayoutCS; return true; } //grab the icon ptr from the icon heap m_qp_cached_trackingIcon = IconHeap::iconHeap()->getIcon(m_trackingIconUids.second,FindIconHint::Copied); if (!m_qp_cached_trackingIcon) { //TODO: TEMP: DEBUG: this doesn't have to end fatally - but until I'm ready for release of the code, i'd like to catch heap-fail problems explicitly //DIE!!! qCritical() << __PRETTY_FUNCTION__ << ": icon heap doesn't have icon uid " << m_trackingIconUids.second; /// <<<--- This should abort the whole process return true; } // QDrag *drag = new QDrag(baseGestureEvent->widget()); // QMimeData *mimeData = new QMimeData; // // mimeData->setText("something"); // drag->setMimeData(mimeData); //// drag->setPixmap(0); // // qDebug() << "exec!"; // Qt::DropAction dropAction = drag->exec(); // qDebug() << "post exec"; m_qp_cached_trackingIcon->slotEnableIconAutoRepaint(); m_qp_cached_trackingIcon->take(this); ///theoretically this could be rejected! //TODO: handling m_qp_cached_trackingIcon->setVisible(true); m_qp_cached_trackingIcon->setPos(positionOfTapICS); m_qp_cached_trackingIcon->update(); return true; }
//! [4] void Mouse::timerEvent(QTimerEvent *) { //! [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; rotate(dx); setPos(mapToParent(0, -(3 + sin(speed) * 3))); }
QgsMapCanvasAnnotationItem::MouseMoveAction QgsMapCanvasAnnotationItem::moveActionForPosition( QPointF pos ) const { QPointF itemPos = mapFromScene( pos ); int cursorSensitivity = 7; if ( mAnnotation && mAnnotation->hasFixedMapPosition() && std::fabs( itemPos.x() ) < cursorSensitivity && std::fabs( itemPos.y() ) < cursorSensitivity ) //move map point if position is close to the origin { return MoveMapPosition; } QPointF offset = mAnnotation && mAnnotation->hasFixedMapPosition() ? mAnnotation->frameOffsetFromReferencePoint() : QPointF( 0, 0 ); QSizeF frameSize = mAnnotation ? mAnnotation->frameSize() : QSizeF( 0, 0 ); bool left, right, up, down; left = std::fabs( itemPos.x() - offset.x() ) < cursorSensitivity; right = std::fabs( itemPos.x() - ( offset.x() + frameSize.width() ) ) < cursorSensitivity; up = std::fabs( itemPos.y() - offset.y() ) < cursorSensitivity; down = std::fabs( itemPos.y() - ( offset.y() + frameSize.height() ) ) < cursorSensitivity; if ( left && up ) { return ResizeFrameLeftUp; } else if ( right && up ) { return ResizeFrameRightUp; } else if ( left && down ) { return ResizeFrameLeftDown; } else if ( right && down ) { return ResizeFrameRightDown; } if ( left ) { return ResizeFrameLeft; } if ( right ) { return ResizeFrameRight; } if ( up ) { return ResizeFrameUp; } if ( down ) { return ResizeFrameDown; } //finally test if pos is in the frame area if ( itemPos.x() >= offset.x() && itemPos.x() <= ( offset.x() + frameSize.width() ) && itemPos.y() >= offset.y() && itemPos.y() <= ( offset.y() + frameSize.height() ) ) { return MoveFramePosition; } return NoAction; }
void CircleObject::updateRubber(QPainter* painter) { int rubberMode = objectRubberMode(); if(rubberMode == OBJ_RUBBER_CIRCLE_1P_RAD) { QPointF sceneCenterPoint = objectRubberPoint("CIRCLE_CENTER"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_RADIUS"); QPointF itemCenterPoint = mapFromScene(sceneCenterPoint); QPointF itemQSnapPoint = mapFromScene(sceneQSnapPoint); QLineF itemLine(itemCenterPoint, itemQSnapPoint); setObjectCenter(sceneCenterPoint); QLineF sceneLine(sceneCenterPoint, sceneQSnapPoint); qreal radius = sceneLine.length(); setObjectRadius(radius); if(painter) painter->drawLine(itemLine); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_1P_DIA) { QPointF sceneCenterPoint = objectRubberPoint("CIRCLE_CENTER"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_DIAMETER"); QPointF itemCenterPoint = mapFromScene(sceneCenterPoint); QPointF itemQSnapPoint = mapFromScene(sceneQSnapPoint); QLineF itemLine(itemCenterPoint, itemQSnapPoint); setObjectCenter(sceneCenterPoint); QLineF sceneLine(sceneCenterPoint, sceneQSnapPoint); qreal diameter = sceneLine.length(); setObjectDiameter(diameter); if(painter) painter->drawLine(itemLine); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_2P) { QPointF sceneTan1Point = objectRubberPoint("CIRCLE_TAN1"); QPointF sceneQSnapPoint = objectRubberPoint("CIRCLE_TAN2"); QLineF sceneLine(sceneTan1Point, sceneQSnapPoint); setObjectCenter(sceneLine.pointAt(0.5)); qreal diameter = sceneLine.length(); setObjectDiameter(diameter); updatePath(); } else if(rubberMode == OBJ_RUBBER_CIRCLE_3P) { QPointF sceneTan1Point = objectRubberPoint("CIRCLE_TAN1"); QPointF sceneTan2Point = objectRubberPoint("CIRCLE_TAN2"); QPointF sceneTan3Point = objectRubberPoint("CIRCLE_TAN3"); double sceneCenterX; double sceneCenterY; getArcCenter(sceneTan1Point.x(), sceneTan1Point.y(), sceneTan2Point.x(), sceneTan2Point.y(), sceneTan3Point.x(), sceneTan3Point.y(), &sceneCenterX, &sceneCenterY); QPointF sceneCenterPoint(sceneCenterX, sceneCenterY); QLineF sceneLine(sceneCenterPoint, sceneTan3Point); setObjectCenter(sceneCenterPoint); qreal radius = sceneLine.length(); setObjectRadius(radius); updatePath(); } }
void Panned::slotEnsurePositionPointerInView(bool page) { if (!m_pointerVisible || !scene()) return; // scroll horizontally only double x = m_pointerTop.x(); double y = m_pointerTop.y(); //!!! n.b. should probably behave differently if the pointer is //!!! not full height int hMin = horizontalScrollBar()->minimum(); int hMax = horizontalScrollBar()->maximum(); double leftDist = 0.15; double rightDist = 0.15; int w = width(); // View width in pixels QRectF r = mapToScene(0, 0, w, 1).boundingRect(); double ws = r.width(); // View width in scene units double left = r.x(); // View left x in scene units double right = left + ws; // View right x in scene units QRectF sr = sceneRect(); double length = sr.width(); // Scene horizontal length double x1 = sr.x(); // Scene x minimum value double x2 = x1 + length; // Scene x maximum value double leftThreshold = left + ws * leftDist; double rightThreshold = right - ws * rightDist; // double delta = x - leftThreshold; // Is x inside the scene? If not do nothing. if ((x < x1) || (x > x2)) return; // std::cerr << "page = " << page << std::endl; int value = horizontalScrollBar()->value(); // std::cerr << "x = " << x << ", left = " << left << ", leftThreshold = " << leftThreshold << ", right = " << right << ", rightThreshold = " << rightThreshold << std::endl; // Is x inside the view? // if (x < leftThreshold || (x > rightThreshold && x < right && page)) { // Allow a little room for x to overshoot the left threshold when the scrollbar is updated. if (x < leftThreshold - 100 || (x > rightThreshold && x < right && page)) { // std::cerr << "big scroll (x is off left, or paging)" << std::endl; // scroll to have the left of the view, plus threshold, at x value = hMin + (((x - ws * leftDist) - x1) * (hMax - hMin)) / (length - ws); } else if (x > rightThreshold) { // std::cerr << "small scroll (x is off right and not paging)" << std::endl; value = hMin + (((x - ws * (1.0 - rightDist)) - x1) * (hMax - hMin)) / (length - ws); } if (value < hMin) value = hMin; else if (value > hMax) value = hMax; // If pointer doesn't fit vertically inside current view, // mouseMoveEvent may be called from scene when ensureVisible() // is called. // Then setupMouseEvent() and setCurrentStaff() will be called from scene. // Then slotUpdatePointerPosition() and slotpointerPositionChanged() will // be called from NotationWidget. // Then again Panned::slotEnsurePositionPointerInView() and probably the // is moved again : this is an infinite recursive call loop which leads to // crash. // To avoid it, ensureVisible() should not be called on a rectangle // highter than the view : // Convert pointer height from scene coords to pixels int hPointerPx = mapFromScene(0, 0, 1, m_pointerHeight).boundingRect().height(); // Compute new pointer height and margin to ensure than pointer + margin // vertically fit inside current view (default ensureVisible() margins // are 50 pixels) double ph; // New height to call ensureVisible() double ymargin; // New vertical margin to call ensureVisible() int h = height(); if (h < hPointerPx) { // If pointer is taller than view replace it with a smaller object // and use null margins ph = (m_pointerHeight * h) / hPointerPx; ymargin = 0; } else if (h < (hPointerPx + 100)) { // If pointer is smaller than view but taller than view + margins // keep pointer as is but use null margins ph = m_pointerHeight; ymargin = 0; } else { // Sizes are OK : don't change anything ph = m_pointerHeight; ymargin = 50; // Keep default margin } // before h scroll if (y != 0) { if (ph > 6) ph = ph - 5; // for safety ensureVisible(QRectF(x, y, 1, ph), 50, ymargin); } horizontalScrollBar()->setValue(value); }
NonPdfFrameHandle::NonPdfFrameHandle (QGraphicsScene &scene, QGraphicsView &view, const QPointF &pointReference, int orientationFlags, NonPdfCropping &nonPdfCropping, int zValue) : m_nonPdfCropping (nonPdfCropping), m_orientationFlags (orientationFlags), m_disableEventsWhileMovingAutomatically (false), m_scene (scene), m_view (view) { const double SUBTLE_OPACITY = 0.2; // Advantages of using ItemIgnoresTransformations: // 1) handles do not get bigger or smaller depending on the size of the image // 2) handles never get ugly when zoomed in // 3) handles never get too tiny when zoomed out // Disadvantages of using ItemIgnoresTransformation: // 1) Resizing the preview window with ItemIgnoresTransformations moves the handles out of position // 2) More conversions back and forth between untransformed and transformed coordinates. This was the deal breaker since // the transformations were undocumented and ultimately too difficult // The solution is to have constant-size handles WITHOUT ItemIgnoresTransformations. This means resizing the window // also involves resizing the handles, but everything else is pretty easy // // ItemIgnoresTransformations flag must agree with the QGraphicsRectItem used for the frame box by PdfCropping setFlags (QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsScenePositionChanges); // Fill with nice color for better visibility. Note that the pen is disabled by overriding the paint method setBrush (QBrush (Qt::blue)); setVisible (true); setZValue (zValue); setOpacity (SUBTLE_OPACITY); setPos (pointReference); // Point position is handled in scene/view coordinates // Add to scene scene.addItem (this); QSize handleSize = m_nonPdfCropping.windowSize() / HANDLE_SIZE_AS_FRACTION_OF_WINDOW_SIZE; // Adjust positions of handles that are not at the top left so handles are laid out symmetrically QPointF pointPos = pointReference; if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_LEFT) != 0) { pointPos.setX (pointPos.x() - handleSize.width() / 2.0); } else if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_RIGHT) != 0) { pointPos.setX (pointPos.x() + handleSize.width() / 2.0); } if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_TOP) != 0) { pointPos.setY (pointPos.y() - handleSize.height() / 2.0); } else if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_BOTTOM) != 0) { pointPos.setY (pointPos.y() + handleSize.height() / 2.0); } // Start with geometry. Since point positions are handled in scene/view coordinates, we have to convert // to local coordinates for the rectangle QPointF topLeftLocal = mapFromScene (pointPos); setRect (QRectF (topLeftLocal, handleSize)); }
/** Handle the user-induced transformation from \a initial_selection_rect to \a new_selection_rect */ void PartEllipse::handleUserTransformation(const QRectF &initial_selection_rect, const QRectF &new_selection_rect) { QList<QPointF> mapped_points = mapPoints(initial_selection_rect, new_selection_rect, saved_points_); setRect(QRectF(mapFromScene(mapped_points.at(0)), mapFromScene(mapped_points.at(1)))); }
void QQuickPinchArea::updatePinch() { Q_D(QQuickPinchArea); QQuickWindow *win = window(); if (d->touchPoints.count() < 2) { setKeepMouseGrab(false); QQuickWindow *c = window(); if (c && c->mouseGrabberItem() == this) ungrabMouse(); } if (d->touchPoints.count() == 0) { if (d->inPinch) { d->inPinch = false; QPointF pinchCenter = mapFromScene(d->sceneLastCenter); QQuickPinchEvent pe(pinchCenter, d->pinchLastScale, d->pinchLastAngle, d->pinchRotation); pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(pinchCenter); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(mapFromScene(d->lastPoint1)); pe.setPoint2(mapFromScene(d->lastPoint2)); emit pinchFinished(&pe); d->pinchStartDist = 0; d->pinchActivated = false; if (d->pinch && d->pinch->target()) d->pinch->setActive(false); } d->initPinch = false; d->pinchRejected = false; d->stealMouse = false; return; } QTouchEvent::TouchPoint touchPoint1 = d->touchPoints.at(0); QTouchEvent::TouchPoint touchPoint2 = d->touchPoints.at(d->touchPoints. count() >= 2 ? 1 : 0); if (touchPoint1.state() == Qt::TouchPointPressed) d->sceneStartPoint1 = touchPoint1.scenePos(); if (touchPoint2.state() == Qt::TouchPointPressed) d->sceneStartPoint2 = touchPoint2.scenePos(); QRectF bounds = clipRect(); // Pinch is not started unless there are exactly two touch points // AND one or more of the points has just now been pressed (wasn't pressed already) // AND both points are inside the bounds. if (d->touchPoints.count() == 2 && (touchPoint1.state() & Qt::TouchPointPressed || touchPoint2.state() & Qt::TouchPointPressed) && bounds.contains(touchPoint1.pos()) && bounds.contains(touchPoint2.pos())) { d->id1 = touchPoint1.id(); d->pinchActivated = true; d->initPinch = true; int touchMouseId = QQuickWindowPrivate::get(win)->touchMouseId; if (touchPoint1.id() == touchMouseId || touchPoint2.id() == touchMouseId) { if (win && win->mouseGrabberItem() != this) { grabMouse(); } } } if (d->pinchActivated && !d->pinchRejected) { const int dragThreshold = qApp->styleHints()->startDragDistance(); QPointF p1 = touchPoint1.scenePos(); QPointF p2 = touchPoint2.scenePos(); qreal dx = p1.x() - p2.x(); qreal dy = p1.y() - p2.y(); qreal dist = sqrt(dx*dx + dy*dy); QPointF sceneCenter = (p1 + p2)/2; qreal angle = QLineF(p1, p2).angle(); if (d->touchPoints.count() == 1) { // If we only have one point then just move the center if (d->id1 == touchPoint1.id()) sceneCenter = d->sceneLastCenter + touchPoint1.scenePos() - d->lastPoint1; else sceneCenter = d->sceneLastCenter + touchPoint2.scenePos() - d->lastPoint2; angle = d->pinchLastAngle; } d->id1 = touchPoint1.id(); if (angle > 180) angle -= 360; if (!d->inPinch || d->initPinch) { if (d->touchPoints.count() >= 2) { if (d->initPinch) { if (!d->inPinch) d->pinchStartDist = dist; d->initPinch = false; } d->sceneStartCenter = sceneCenter; d->sceneLastCenter = sceneCenter; d->pinchStartCenter = mapFromScene(sceneCenter); d->pinchStartAngle = angle; d->pinchLastScale = 1.0; d->pinchLastAngle = angle; d->pinchRotation = 0.0; d->lastPoint1 = p1; d->lastPoint2 = p2; if (qAbs(dist - d->pinchStartDist) >= dragThreshold || (pinch()->axis() != QQuickPinch::NoDrag && (qAbs(p1.x()-d->sceneStartPoint1.x()) >= dragThreshold || qAbs(p1.y()-d->sceneStartPoint1.y()) >= dragThreshold || qAbs(p2.x()-d->sceneStartPoint2.x()) >= dragThreshold || qAbs(p2.y()-d->sceneStartPoint2.y()) >= dragThreshold))) { QQuickPinchEvent pe(d->pinchStartCenter, 1.0, angle, 0.0); d->pinchStartDist = dist; pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(d->pinchStartCenter); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(mapFromScene(d->lastPoint1)); pe.setPoint2(mapFromScene(d->lastPoint2)); pe.setPointCount(d->touchPoints.count()); emit pinchStarted(&pe); if (pe.accepted()) { d->inPinch = true; d->stealMouse = true; if (win && win->mouseGrabberItem() != this) grabMouse(); setKeepMouseGrab(true); grabTouchPoints(QVector<int>() << touchPoint1.id() << touchPoint2.id()); d->inPinch = true; d->stealMouse = true; if (d->pinch && d->pinch->target()) { d->pinchStartPos = pinch()->target()->position(); d->pinchStartScale = d->pinch->target()->scale(); d->pinchStartRotation = d->pinch->target()->rotation(); d->pinch->setActive(true); } } else { d->pinchRejected = true; } } } } else if (d->pinchStartDist > 0) { qreal scale = dist ? dist / d->pinchStartDist : d->pinchLastScale; qreal da = d->pinchLastAngle - angle; if (da > 180) da -= 360; else if (da < -180) da += 360; d->pinchRotation += da; QPointF pinchCenter = mapFromScene(sceneCenter); QQuickPinchEvent pe(pinchCenter, scale, angle, d->pinchRotation); pe.setStartCenter(d->pinchStartCenter); pe.setPreviousCenter(mapFromScene(d->sceneLastCenter)); pe.setPreviousAngle(d->pinchLastAngle); pe.setPreviousScale(d->pinchLastScale); pe.setStartPoint1(mapFromScene(d->sceneStartPoint1)); pe.setStartPoint2(mapFromScene(d->sceneStartPoint2)); pe.setPoint1(touchPoint1.pos()); pe.setPoint2(touchPoint2.pos()); pe.setPointCount(d->touchPoints.count()); d->pinchLastScale = scale; d->sceneLastCenter = sceneCenter; d->pinchLastAngle = angle; d->lastPoint1 = touchPoint1.scenePos(); d->lastPoint2 = touchPoint2.scenePos(); emit pinchUpdated(&pe); if (d->pinch && d->pinch->target()) { qreal s = d->pinchStartScale * scale; s = qMin(qMax(pinch()->minimumScale(),s), pinch()->maximumScale()); pinch()->target()->setScale(s); QPointF pos = sceneCenter - d->sceneStartCenter + d->pinchStartPos; if (pinch()->axis() & QQuickPinch::XAxis) { qreal x = pos.x(); if (x < pinch()->xmin()) x = pinch()->xmin(); else if (x > pinch()->xmax()) x = pinch()->xmax(); pinch()->target()->setX(x); } if (pinch()->axis() & QQuickPinch::YAxis) { qreal y = pos.y(); if (y < pinch()->ymin()) y = pinch()->ymin(); else if (y > pinch()->ymax()) y = pinch()->ymax(); pinch()->target()->setY(y); } if (d->pinchStartRotation >= pinch()->minimumRotation() && d->pinchStartRotation <= pinch()->maximumRotation()) { qreal r = d->pinchRotation + d->pinchStartRotation; r = qMin(qMax(pinch()->minimumRotation(),r), pinch()->maximumRotation()); pinch()->target()->setRotation(r); } } } } }