diff options
Diffstat (limited to 'src/gui/graphicsview/qgraphicsview.cpp')
-rw-r--r-- | src/gui/graphicsview/qgraphicsview.cpp | 995 |
1 files changed, 395 insertions, 600 deletions
diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 09937f3..07dc6ad 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -39,8 +39,6 @@ ** ****************************************************************************/ -//#define QGRAPHICSVIEW_DEBUG - static const int QGRAPHICSVIEW_REGION_RECT_THRESHOLD = 50; static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < 2^9 @@ -50,9 +48,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < \brief The QGraphicsView class provides a widget for displaying the contents of a QGraphicsScene. \since 4.2 - \ingroup multimedia \ingroup graphicsview-api - \mainclass + QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable viewport. To create a scene with geometrical items, see QGraphicsScene's @@ -99,8 +96,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < setViewport(new QGLWidget). QGraphicsView takes ownership of the viewport widget. - QGraphicsView supports affine transformations, using QMatrix. You can - either pass a matrix to setMatrix(), or you can call one of the + QGraphicsView supports affine transformations, using QTransform. You can + either pass a matrix to setTransform(), or you can call one of the convenience functions rotate(), scale(), translate() or shear(). The most two common transformations are scaling, which is used to implement zooming, and rotation. QGraphicsView keeps the center of the view fixed @@ -200,16 +197,7 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < Note that setting a flag usually imposes a side effect, and this effect can vary between paint devices and platforms. - \value DontClipPainter QGraphicsView sometimes clips the painter when - rendering the scene contents. This can generally improve performance - (e.g., rendering only small parts of a large pixmap), and protects against - rendering mistakes (e.g., drawing outside bounding rectangles, or outside - the exposed area). In some situations, however, the painter clip can slow - down rendering; especially when all painting is restricted to inside - exposed areas. By enabling this flag, QGraphicsView will completely - disable its implicit clipping. Note that rendering artifacts from using a - semi-transparent foreground or background brush can occur if clipping is - disabled. + \value DontClipPainter This value is obsolete and has no effect. \value DontSavePainterState When rendering, QGraphicsView protects the painter state (see QPainter::save()) when rendering the background or @@ -228,6 +216,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < minimizing the areas that require redrawing, which improves performance. A common side effect is that items that do draw with antialiasing can leave painting traces behind on the scene as they are moved. + + \omitvalue IndirectPainting */ /*! @@ -289,12 +279,17 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < #include <QtGui/qpainter.h> #include <QtGui/qscrollbar.h> #include <QtGui/qstyleoption.h> +#include <QtGui/qinputcontext.h> #ifdef Q_WS_X11 #include <private/qt_x11_p.h> #endif +#include <private/qevent_p.h> + QT_BEGIN_NAMESPACE +bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); + inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for single precision { if (d <= (qreal) INT_MIN) @@ -304,6 +299,23 @@ inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for sing return d >= 0.0 ? int(d + 0.5) : int(d - int(d-1) + 0.5) + int(d-1); } +void QGraphicsViewPrivate::translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent) +{ + QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints(); + for (int i = 0; i < touchPoints.count(); ++i) { + QTouchEvent::TouchPoint &touchPoint = touchPoints[i]; + // the scene will set the item local pos, startPos, lastPos, and rect before delivering to + // an item, but for now those functions are returning the view's local coordinates + touchPoint.setSceneRect(d->mapToScene(touchPoint.rect())); + touchPoint.setStartScenePos(d->mapToScene(touchPoint.startPos())); + touchPoint.setLastScenePos(d->mapToScene(touchPoint.lastPos())); + + // screenPos, startScreenPos, lastScreenPos, and screenRect are already set + } + + touchEvent->setTouchPoints(touchPoints); +} + /*! \internal */ @@ -338,8 +350,6 @@ QGraphicsViewPrivate::QGraphicsViewPrivate() #endif lastDragDropEvent(0), fullUpdatePending(true), - dirtyRectCount(0), - updatingLater(false), updateSceneSlotReimplementedChecked(false) { styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS); @@ -400,7 +410,7 @@ void QGraphicsViewPrivate::recalculateContentSize() int left = q_round_bound(viewRect.left()); int right = q_round_bound(viewRect.right() - width); if (left >= right) { - q->horizontalScrollBar()->setRange(0, 0); + hbar->setRange(0, 0); switch (alignment & Qt::AlignHorizontal_Mask) { case Qt::AlignLeft: @@ -415,9 +425,9 @@ void QGraphicsViewPrivate::recalculateContentSize() break; } } else { - q->horizontalScrollBar()->setRange(left, right); - q->horizontalScrollBar()->setPageStep(width); - q->horizontalScrollBar()->setSingleStep(width / 20); + hbar->setRange(left, right); + hbar->setPageStep(width); + hbar->setSingleStep(width / 20); leftIndent = 0; } @@ -426,7 +436,7 @@ void QGraphicsViewPrivate::recalculateContentSize() int top = q_round_bound(viewRect.top()); int bottom = q_round_bound(viewRect.bottom() - height); if (top >= bottom) { - q->verticalScrollBar()->setRange(0, 0); + vbar->setRange(0, 0); switch (alignment & Qt::AlignVertical_Mask) { case Qt::AlignTop: @@ -441,9 +451,9 @@ void QGraphicsViewPrivate::recalculateContentSize() break; } } else { - q->verticalScrollBar()->setRange(top, bottom); - q->verticalScrollBar()->setPageStep(height); - q->verticalScrollBar()->setSingleStep(height / 20); + vbar->setRange(top, bottom); + vbar->setPageStep(height); + vbar->setSingleStep(height / 20); topIndent = 0; } @@ -455,7 +465,7 @@ void QGraphicsViewPrivate::recalculateContentSize() // scroll instead. if (oldLeftIndent != leftIndent || oldTopIndent != topIndent) { dirtyScroll = true; - q->viewport()->update(); + updateAll(); } else if (q->isRightToLeft() && !leftIndent) { // In reverse mode, the horizontal scroll always changes after the content // size has changed, as the scroll is calculated by summing the min and @@ -481,9 +491,9 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor) if (q->underMouse()) { // Last scene pos: lastMouseMoveScenePoint // Current mouse pos: - QPointF transformationDiff = q->mapToScene(q->viewport()->rect().center()) - - q->mapToScene(q->mapFromGlobal(QCursor::pos())); - q->centerOn(lastMouseMoveScenePoint + transformationDiff);; + QPointF transformationDiff = q->mapToScene(viewport->rect().center()) + - q->mapToScene(viewport->mapFromGlobal(QCursor::pos())); + q->centerOn(lastMouseMoveScenePoint + transformationDiff); } else { q->centerOn(lastCenterPoint); } @@ -503,7 +513,7 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor) void QGraphicsViewPrivate::updateLastCenterPoint() { Q_Q(QGraphicsView); - lastCenterPoint = q->mapToScene(q->viewport()->rect().center()); + lastCenterPoint = q->mapToScene(viewport->rect().center()); } /*! @@ -541,15 +551,15 @@ void QGraphicsViewPrivate::updateScroll() scrollX = qint64(-leftIndent); if (q->isRightToLeft()) { if (!leftIndent) { - scrollX += q->horizontalScrollBar()->minimum(); - scrollX += q->horizontalScrollBar()->maximum(); - scrollX -= q->horizontalScrollBar()->value(); + scrollX += hbar->minimum(); + scrollX += hbar->maximum(); + scrollX -= hbar->value(); } } else { - scrollX += q->horizontalScrollBar()->value(); + scrollX += hbar->value(); } - scrollY = qint64(q->verticalScrollBar()->value() - topIndent); + scrollY = qint64(vbar->value() - topIndent); dirtyScroll = false; } @@ -589,7 +599,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) return; QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove); - mouseEvent.setWidget(q->viewport()); + mouseEvent.setWidget(viewport); mouseEvent.setButtonDownScenePos(mousePressButton, mousePressScenePoint); mouseEvent.setButtonDownScreenPos(mousePressButton, mousePressScreenPoint); mouseEvent.setScenePos(q->mapToScene(event->pos())); @@ -602,7 +612,10 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) lastMouseMoveScenePoint = mouseEvent.scenePos(); lastMouseMoveScreenPoint = mouseEvent.screenPos(); mouseEvent.setAccepted(false); - QApplication::sendEvent(scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(scene, &mouseEvent); + else + QApplication::sendEvent(scene, &mouseEvent); // Remember whether the last event was accepted or not. lastMouseEvent.setAccepted(mouseEvent.isAccepted()); @@ -614,6 +627,16 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) } #ifndef QT_NO_CURSOR + // If all the items ignore hover events, we don't look-up any items + // in QGraphicsScenePrivate::dispatchHoverEvent, hence the + // cachedItemsUnderMouse list will be empty. We therefore do the look-up + // for cursor items here if not all items use the default cursor. + if (scene->d_func()->allItemsIgnoreHoverEvents && !scene->d_func()->allItemsUseDefaultCursor + && scene->d_func()->cachedItemsUnderMouse.isEmpty()) { + scene->d_func()->cachedItemsUnderMouse = scene->d_func()->itemsAtPosition(mouseEvent.screenPos(), + mouseEvent.scenePos(), + mouseEvent.widget()); + } // Find the topmost item under the mouse with a cursor. foreach (QGraphicsItem *item, scene->d_func()->cachedItemsUnderMouse) { if (item->hasCursor()) { @@ -626,7 +649,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) if (hasStoredOriginalCursor) { // Restore the original viewport cursor. hasStoredOriginalCursor = false; - q->viewport()->setCursor(originalCursor); + viewport->setCursor(originalCursor); } #endif } @@ -658,8 +681,6 @@ QRegion QGraphicsViewPrivate::rubberBandRegion(const QWidget *widget, const QRec #ifndef QT_NO_CURSOR void QGraphicsViewPrivate::_q_setViewportCursor(const QCursor &cursor) { - Q_Q(QGraphicsView); - QWidget *viewport = q->viewport(); if (!hasStoredOriginalCursor) { hasStoredOriginalCursor = true; originalCursor = viewport->cursor(); @@ -685,9 +706,9 @@ void QGraphicsViewPrivate::_q_unsetViewportCursor() // Restore the original viewport cursor. hasStoredOriginalCursor = false; if (dragMode == QGraphicsView::ScrollHandDrag) - q->viewport()->setCursor(Qt::OpenHandCursor); + viewport->setCursor(Qt::OpenHandCursor); else - q->viewport()->setCursor(originalCursor); + viewport->setCursor(originalCursor); } #endif @@ -726,7 +747,7 @@ void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEven dest->setProposedAction(source->proposedAction()); dest->setDropAction(source->dropAction()); dest->setMimeData(source->mimeData()); - dest->setWidget(q->viewport()); + dest->setWidget(viewport); dest->setSource(source->source()); #else Q_UNUSED(dest) @@ -749,12 +770,13 @@ QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRect } // Translate-only + // COMBINE QPointF offset; const QGraphicsItem *parentItem = item; const QGraphicsItemPrivate *itemd; do { - itemd = parentItem->d_ptr; - if (itemd->hasTransform) + itemd = parentItem->d_ptr.data(); + if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); @@ -786,241 +808,120 @@ QRegion QGraphicsViewPrivate::mapToViewRegion(const QGraphicsItem *item, const Q const_cast<QGraphicsViewPrivate *>(this)->updateScroll(); // Accurate bounding region - QTransform itv = item->sceneTransform() * q->viewportTransform(); + QTransform itv = item->deviceTransform(q->viewportTransform()); return item->boundingRegion(itv) & itv.mapRect(rect).toAlignedRect(); } -// QRectF::intersects() returns false always if either the source or target -// rectangle's width or height are 0. This works around that problem. -static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item) -{ - Q_ASSERT(item); - QRectF boundingRect(item->boundingRect()); - if (!boundingRect.width()) - boundingRect.adjust(-0.00001, 0, 0.00001, 0); - if (!boundingRect.height()) - boundingRect.adjust(0, -0.00001, 0, 0.00001); - return boundingRect; -} - /*! \internal */ -void QGraphicsViewPrivate::itemUpdated(QGraphicsItem *item, const QRectF &rect) -{ - if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate) - return; - if (item->d_ptr->dirty) - updateLater(); - - QRectF updateRect = rect; - if ((item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) || item->d_ptr->children.isEmpty()) { - updateRect &= adjustedItemBoundingRect(item); - if (updateRect.isEmpty()) - return; - } - - QGraphicsItem *clipItem = item; - if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) { - // Minimize unnecessary redraw. - QGraphicsItem *parent = item; - while ((parent = parent->d_ptr->parent)) { - if (parent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) { - // Map update rect to the current parent and itersect with its bounding rect. - updateRect = clipItem->itemTransform(parent).mapRect(updateRect) - & adjustedItemBoundingRect(parent); - if (updateRect.isEmpty()) - return; - clipItem = parent; - } - - if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) - break; - } - } - - // Map update rect from clipItem coordinates to view coordinates. - Q_ASSERT(clipItem); - if (!item->d_ptr->hasBoundingRegionGranularity) - this->updateRect(mapToViewRect(clipItem, updateRect) & viewport->rect()); - else - updateRegion(mapToViewRegion(clipItem, updateRect) & viewport->rect()); -} - -void QGraphicsViewPrivate::updateLater() -{ - Q_Q(QGraphicsView); - if (updatingLater) - return; - updatingLater = true; - QMetaObject::invokeMethod(q, "_q_updateLaterSlot", Qt::QueuedConnection); -} - -void QGraphicsViewPrivate::_q_updateLaterSlot() +void QGraphicsViewPrivate::processPendingUpdates() { - Q_Q(QGraphicsView); if (!scene) return; - QRect vr = viewport->rect(); - QTransform viewTransform = q->viewportTransform(); - const QList<QGraphicsItem *> &dirtyItems = scene->d_func()->dirtyItems; - for (int i = 0; i < dirtyItems.size(); ++i) { - const QGraphicsItem *item = dirtyItems.at(i); - if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/false, - /*ignoreVisibleBit=*/false, - /*ignoreDirtyBit=*/true)) { - continue; - } - QTransform x = item->sceneTransform() * viewTransform; - updateRect(x.mapRect(item->boundingRect()).toAlignedRect() & vr); - } - - dirtyRectCount += dirtyRects.size(); - - bool noUpdate = !fullUpdatePending && viewportUpdateMode == QGraphicsView::FullViewportUpdate; - if ((dirtyRectCount > 0 || !dirtyBoundingRect.isEmpty()) && !fullUpdatePending && !noUpdate) { - if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate - || (viewportUpdateMode == QGraphicsView::SmartViewportUpdate - && dirtyRectCount >= QGRAPHICSVIEW_REGION_RECT_THRESHOLD)) { - if (!(optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)) { - viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); - } else { - viewport->update(dirtyBoundingRect); - } - } else { - // ### Improve this block, which is very slow for complex regions. We - // need to strike the balance between having an accurate update - // region, and running fast. The below approach is the simplest way to - // create a region from a bunch of rects, but we might want to use - // other approaches; e.g., a grid of a fixed size representing - // quadrants of the viewport, which we mark as dirty depending on the - // rectangles in the list. Perhaps this should go into a - // QRegion::fromRects(rects, how) function. - QRegion region; - if (!(optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)) { - for (int i = 0; i < dirtyRegions.size(); ++i) { - QVector<QRect> rects = dirtyRegions.at(i).rects(); - for (int j = 0; j < rects.size(); ++j) - region += rects.at(j).adjusted(-2, -2, 2, 2); - } - for (int i = 0; i < dirtyRects.size(); ++i) - region += dirtyRects.at(i).adjusted(-2, -2, 2, 2); - } else { - for (int i = 0; i < dirtyRegions.size(); ++i) - region += dirtyRegions.at(i); - for (int i = 0; i < dirtyRects.size(); ++i) - region += dirtyRects.at(i); - } - - viewport->update(region); - } + if (fullUpdatePending) { + viewport->update(); + } else if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + viewport->update(dirtyBoundingRect.adjusted(-1, -1, 1, 1)); + else + viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); + } else { + viewport->update(dirtyRegion); // Already adjusted in updateRect/Region. } - dirtyRegions.clear(); - dirtyRects.clear(); - dirtyRectCount = 0; dirtyBoundingRect = QRect(); - updatingLater = false; + dirtyRegion = QRegion(); } -void QGraphicsViewPrivate::updateAll() +static inline bool intersectsViewport(const QRect &r, int width, int height) +{ return !(r.left() > width) && !(r.right() < 0) && !(r.top() >= height) && !(r.bottom() < 0); } + +static inline bool containsViewport(const QRect &r, int width, int height) +{ return r.left() <= 0 && r.top() <= 0 && r.right() >= width - 1 && r.bottom() >= height - 1; } + +static inline void QRect_unite(QRect *rect, const QRect &other) { - Q_Q(QGraphicsView); - q->viewport()->update(); - fullUpdatePending = true; - dirtyRectCount = 0; - dirtyBoundingRect = QRect(); - updatingLater = false; + if (rect->isEmpty()) { + *rect = other; + } else { + rect->setCoords(qMin(rect->left(), other.left()), qMin(rect->top(), other.top()), + qMax(rect->right(), other.right()), qMax(rect->bottom(), other.bottom())); + } } -void QGraphicsViewPrivate::updateRegion(const QRegion &r) +bool QGraphicsViewPrivate::updateRegion(const QRegion &r) { - if (r.isEmpty()) - return; + if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate || r.isEmpty()) + return false; - Q_Q(QGraphicsView); + const QRect boundingRect = r.boundingRect(); + if (!intersectsViewport(boundingRect, viewport->width(), viewport->height())) + return false; // Update region outside viewport. - // Rect intersects viewport - update everything? switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); break; case QGraphicsView::BoundingRectViewportUpdate: - dirtyBoundingRect |= r.boundingRect(); - if (dirtyBoundingRect == q->viewport()->rect()) { + QRect_unite(&dirtyBoundingRect, boundingRect); + if (containsViewport(dirtyBoundingRect, viewport->width(), viewport->height())) { fullUpdatePending = true; - q->viewport()->update(); - } else { - updateLater(); + viewport->update(); } break; - case QGraphicsView::SmartViewportUpdate: - dirtyBoundingRect |= r.boundingRect(); - if ((dirtyRectCount + r.numRects()) < QGRAPHICSVIEW_REGION_RECT_THRESHOLD) - dirtyRegions << r; - dirtyRectCount += r.numRects(); - updateLater(); - break; + case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: - dirtyRegions << r; - dirtyRectCount += r.numRects(); - updateLater(); + { + const QVector<QRect> &rects = r.rects(); + for (int i = 0; i < rects.size(); ++i) { + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + dirtyRegion += rects.at(i).adjusted(-1, -1, 1, 1); + else + dirtyRegion += rects.at(i).adjusted(-2, -2, 2, 2); + } break; - case QGraphicsView::NoViewportUpdate: - // Unreachable + } + default: break; } - // Compress the regions... - if (dirtyRectCount > QGRAPHICSVIEW_REGION_RECT_THRESHOLD && dirtyRegions.size() > 1) { - QRegion masterRegion; - for (int i=0; i<dirtyRegions.size(); ++i) { - masterRegion |= dirtyRegions.at(i); - } - dirtyRectCount = masterRegion.numRects(); - dirtyRegions.clear(); - dirtyRegions << masterRegion; - } + return true; } -void QGraphicsViewPrivate::updateRect(const QRect &r) +bool QGraphicsViewPrivate::updateRect(const QRect &r) { - if (r.isEmpty()) - return; - - Q_Q(QGraphicsView); + if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate + || !intersectsViewport(r, viewport->width(), viewport->height())) { + return false; + } - // Rect intersects viewport - update everything? switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); break; case QGraphicsView::BoundingRectViewportUpdate: - dirtyBoundingRect |= r; - if (dirtyBoundingRect == q->viewport()->rect()) { + QRect_unite(&dirtyBoundingRect, r); + if (containsViewport(dirtyBoundingRect, viewport->width(), viewport->height())) { fullUpdatePending = true; - q->viewport()->update(); - } else { - updateLater(); + viewport->update(); } break; - case QGraphicsView::SmartViewportUpdate: - dirtyBoundingRect |= r; - if ((dirtyRectCount + dirtyRects.size()) < QGRAPHICSVIEW_REGION_RECT_THRESHOLD) - dirtyRects << r; - updateLater(); - break; + case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: - dirtyRects << r; - updateLater(); + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + dirtyRegion += r.adjusted(-1, -1, 1, 1); + else + dirtyRegion += r.adjusted(-2, -2, 2, 2); break; - case QGraphicsView::NoViewportUpdate: - // Unreachable + default: break; } + + return true; } QStyleOptionGraphicsItem *QGraphicsViewPrivate::allocStyleOptionsArray(int numItems) @@ -1055,47 +956,32 @@ extern QPainterPath qt_regionToPath(const QRegion ®ion); is at risk of painting 1 pixel outside the bounding rect. Therefore we must search for items with an adjustment of (-1, -1, 1, 1). */ -QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedRegion, bool *allItems) const +QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedRegion, bool *allItems, + const QTransform &viewTransform) const { Q_Q(const QGraphicsView); // Step 1) If all items are contained within the expose region, then - // return a list of all visible items. - const QRectF exposedRegionSceneBounds = q->mapToScene(exposedRegion.boundingRect().adjusted(-1, -1, 2, 2)) + // return a list of all visible items. ### the scene's growing bounding + // rect does not take into account untransformable items. + const QRectF exposedRegionSceneBounds = q->mapToScene(exposedRegion.boundingRect().adjusted(-1, -1, 1, 1)) .boundingRect(); - if (exposedRegionSceneBounds.contains(scene->d_func()->growingItemsBoundingRect)) { + if (exposedRegionSceneBounds.contains(scene->sceneRect())) { Q_ASSERT(allItems); *allItems = true; - // All items are guaranteed within the exposed region, don't bother using the index. - QList<QGraphicsItem *> itemList(scene->items()); - int i = 0; - while (i < itemList.size()) { - const QGraphicsItem *item = itemList.at(i); - // But we only want to include items that are visible - // The following check is basically the same as item->d_ptr->isInvisible(), except - // that we don't check whether the item clips children to shape or propagates its - // opacity (we loop through all items, so those checks are wrong in this context). - if (!item->isVisible() || item->d_ptr->isClippedAway() || item->d_ptr->isFullyTransparent()) - itemList.removeAt(i); - else - ++i; - } - - // Sort the items. - QGraphicsScenePrivate::sortItems(&itemList, Qt::DescendingOrder, scene->d_func()->sortCacheEnabled); - return itemList; + // All items are guaranteed within the exposed region. + return scene->items(Qt::DescendingOrder); } // Step 2) If the expose region is a simple rect and the view is only // translated or scaled, search for items using // QGraphicsScene::items(QRectF). - bool simpleRectLookup = (scene->d_func()->largestUntransformableItem.isNull() - && exposedRegion.numRects() == 1 && matrix.type() <= QTransform::TxScale); + bool simpleRectLookup = exposedRegion.numRects() == 1 && matrix.type() <= QTransform::TxScale; if (simpleRectLookup) { - return scene->d_func()->items_helper(exposedRegionSceneBounds, - Qt::IntersectsItemBoundingRect, - Qt::DescendingOrder); + return scene->items(exposedRegionSceneBounds, + Qt::IntersectsItemBoundingRect, + Qt::DescendingOrder, viewTransform); } // If the region is complex or the view has a complex transform, adjust @@ -1105,79 +991,25 @@ QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedReg foreach (const QRect &r, exposedRegion.rects()) adjustedRegion += r.adjusted(-1, -1, 1, 1); - const QPainterPath exposedPath(qt_regionToPath(adjustedRegion)); - if (scene->d_func()->largestUntransformableItem.isNull()) { - const QPainterPath exposedScenePath(q->mapToScene(exposedPath)); - return scene->d_func()->items_helper(exposedScenePath, - Qt::IntersectsItemBoundingRect, - Qt::DescendingOrder); - } - - // NB! Path must be in viewport coordinates. - return itemsInArea(exposedPath, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder); -} - -void QGraphicsViewPrivate::generateStyleOptions(const QList<QGraphicsItem *> &itemList, - QGraphicsItem **itemArray, - QStyleOptionGraphicsItem *styleOptionArray, - const QTransform &worldTransform, - bool allItems, - const QRegion &exposedRegion) const -{ - // Two unit vectors. - QLineF v1(0, 0, 1, 0); - QLineF v2(0, 0, 0, 1); - QTransform itemToViewportTransform; - QRectF brect; - QTransform reverseMap; - - for (int i = 0; i < itemList.size(); ++i) { - QGraphicsItem *item = itemArray[i] = itemList[i]; - - QStyleOptionGraphicsItem &option = styleOptionArray[i]; - brect = item->boundingRect(); - option.state = QStyle::State_None; - option.rect = brect.toRect(); - option.exposedRect = QRectF(); - if (item->d_ptr->selected) - option.state |= QStyle::State_Selected; - if (item->d_ptr->enabled) - option.state |= QStyle::State_Enabled; - if (item->hasFocus()) - option.state |= QStyle::State_HasFocus; - if (scene->d_func()->hoverItems.contains(item)) - option.state |= QStyle::State_MouseOver; - if (item == scene->mouseGrabberItem()) - option.state |= QStyle::State_Sunken; - - // Calculate a simple level-of-detail metric. - // ### almost identical code in QGraphicsScene::render() - // and QGraphicsView::render() - consider refactoring - itemToViewportTransform = item->deviceTransform(worldTransform); - - if (itemToViewportTransform.type() <= QTransform::TxTranslate) { - // Translation and rotation only? The LOD is 1. - option.levelOfDetail = 1; - } else { - // LOD is the transformed area of a 1x1 rectangle. - option.levelOfDetail = qSqrt(itemToViewportTransform.map(v1).length() * itemToViewportTransform.map(v2).length()); - } - option.matrix = itemToViewportTransform.toAffine(); //### discards perspective - - if (!allItems) { - // Determine the item's exposed area - reverseMap = itemToViewportTransform.inverted(); - foreach (const QRect &rect, exposedRegion.rects()) { - option.exposedRect |= reverseMap.mapRect(QRectF(rect.adjusted(-1, -1, 1, 1))); - if (option.exposedRect.contains(brect)) - break; - } - option.exposedRect &= brect; - } else { - // The whole item is exposed - option.exposedRect = brect; - } - } + const QPainterPath exposedScenePath(q->mapToScene(qt_regionToPath(adjustedRegion))); + return scene->items(exposedScenePath, Qt::IntersectsItemBoundingRect, + Qt::DescendingOrder, viewTransform); +} + +/*! + \internal + + Enables input methods for the view if and only if the current focus item of + the scene accepts input methods. Call function whenever that condition has + potentially changed. +*/ +void QGraphicsViewPrivate::updateInputMethodSensitivity() +{ + Q_Q(QGraphicsView); + bool enabled = scene && scene->focusItem() + && (scene->focusItem()->flags() & QGraphicsItem::ItemAcceptsInputMethod); + q->setAttribute(Qt::WA_InputMethodEnabled, enabled); + q->viewport()->setAttribute(Qt::WA_InputMethodEnabled, enabled); } /*! @@ -1189,12 +1021,9 @@ QGraphicsView::QGraphicsView(QWidget *parent) setViewport(0); setAcceptDrops(true); setBackgroundRole(QPalette::Base); - - // ### Ideally this would be enabled/disabled depending on whether any - // widgets in the current scene enabled input methods. We could do that - // using a simple reference count. The same goes for acceptDrops and mouse - // tracking. + // Investigate leaving these disabled by default. setAttribute(Qt::WA_InputMethodEnabled); + viewport()->setAttribute(Qt::WA_InputMethodEnabled); } /*! @@ -1208,7 +1037,9 @@ QGraphicsView::QGraphicsView(QGraphicsScene *scene, QWidget *parent) setViewport(0); setAcceptDrops(true); setBackgroundRole(QPalette::Base); + // Investigate leaving these disabled by default. setAttribute(Qt::WA_InputMethodEnabled); + viewport()->setAttribute(Qt::WA_InputMethodEnabled); } /*! @@ -1220,7 +1051,9 @@ QGraphicsView::QGraphicsView(QGraphicsViewPrivate &dd, QWidget *parent) setViewport(0); setAcceptDrops(true); setBackgroundRole(QPalette::Base); + // Investigate leaving these disabled by default. setAttribute(Qt::WA_InputMethodEnabled); + viewport()->setAttribute(Qt::WA_InputMethodEnabled); } /*! @@ -1274,7 +1107,7 @@ void QGraphicsView::setRenderHints(QPainter::RenderHints hints) if (hints == d->renderHints) return; d->renderHints = hints; - viewport()->update(); + d->updateAll(); } /*! @@ -1292,7 +1125,7 @@ void QGraphicsView::setRenderHint(QPainter::RenderHint hint, bool enabled) else d->renderHints &= ~hint; if (oldHints != d->renderHints) - viewport()->update(); + d->updateAll(); } /*! @@ -1579,7 +1412,7 @@ void QGraphicsView::resetCachedContent() if (d->cacheMode & CacheBackground) { // Background caching is enabled. d->mustResizeBackgroundPixmap = true; - viewport()->update(); + d->updateAll(); } else if (d->mustResizeBackgroundPixmap) { // Background caching is disabled. // Cleanup, free some resources. @@ -1668,7 +1501,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene) return; // Always update the viewport when the scene changes. - viewport()->update(); + d->updateAll(); // Remove the previously assigned scene. if (d->scene) { @@ -1676,7 +1509,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene) this, SLOT(updateScene(QList<QRectF>))); disconnect(d->scene, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(updateSceneRect(QRectF))); - d->scene->d_func()->views.removeAll(this); + d->scene->d_func()->removeView(this); d->connectedToScene = false; } @@ -1685,13 +1518,25 @@ void QGraphicsView::setScene(QGraphicsScene *scene) connect(d->scene, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(updateSceneRect(QRectF))); d->updateSceneSlotReimplementedChecked = false; - d->scene->d_func()->views << this; + d->scene->d_func()->addView(this); d->recalculateContentSize(); d->lastCenterPoint = sceneRect().center(); d->keepLastCenterPoint = true; + // We are only interested in mouse tracking if items accept + // hover events or use non-default cursors. + if (!d->scene->d_func()->allItemsIgnoreHoverEvents + || !d->scene->d_func()->allItemsUseDefaultCursor) { + d->viewport->setMouseTracking(true); + } + + // enable touch events if any items is interested in them + if (!d->scene->d_func()->allItemsIgnoreTouchEvents) + d->viewport->setAttribute(Qt::WA_AcceptTouchEvents); } else { d->recalculateContentSize(); } + + d->updateInputMethodSensitivity(); } /*! @@ -1738,7 +1583,7 @@ void QGraphicsView::setSceneRect(const QRectF &rect) Returns the current transformation matrix for the view. If no current transformation is set, the identity matrix is returned. - \sa setMatrix(), rotate(), scale(), shear(), translate() + \sa setMatrix(), transform(), rotate(), scale(), shear(), translate() */ QMatrix QGraphicsView::matrix() const { @@ -1770,7 +1615,7 @@ QMatrix QGraphicsView::matrix() const a view coordinate to a floating point scene coordinate, or mapFromScene() to map from floating point scene coordinates to view coordinates. - \sa matrix(), rotate(), scale(), shear(), translate() + \sa matrix(), setTransform(), rotate(), scale(), shear(), translate() */ void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine) { @@ -1779,6 +1624,8 @@ void QGraphicsView::setMatrix(const QMatrix &matrix, bool combine) /*! Resets the view transformation matrix to the identity matrix. + + \sa resetTransform() */ void QGraphicsView::resetMatrix() { @@ -1788,7 +1635,7 @@ void QGraphicsView::resetMatrix() /*! Rotates the current view transformation \a angle degrees clockwise. - \sa setMatrix(), matrix(), scale(), shear(), translate() + \sa setTransform(), transform(), scale(), shear(), translate() */ void QGraphicsView::rotate(qreal angle) { @@ -1801,7 +1648,7 @@ void QGraphicsView::rotate(qreal angle) /*! Scales the current view transformation by (\a sx, \a sy). - \sa setMatrix(), matrix(), rotate(), shear(), translate() + \sa setTransform(), transform(), rotate(), shear(), translate() */ void QGraphicsView::scale(qreal sx, qreal sy) { @@ -1814,7 +1661,7 @@ void QGraphicsView::scale(qreal sx, qreal sy) /*! Shears the current view transformation by (\a sh, \a sv). - \sa setMatrix(), matrix(), rotate(), scale(), translate() + \sa setTransform(), transform(), rotate(), scale(), translate() */ void QGraphicsView::shear(qreal sh, qreal sv) { @@ -1827,7 +1674,7 @@ void QGraphicsView::shear(qreal sh, qreal sv) /*! Translates the current view transformation by (\a dx, \a dy). - \sa setMatrix(), matrix(), rotate(), shear() + \sa setTransform(), transform(), rotate(), shear() */ void QGraphicsView::translate(qreal dx, qreal dy) { @@ -1985,7 +1832,7 @@ void QGraphicsView::ensureVisible(const QGraphicsItem *item, int xmargin, int ym If \a rect is empty, or if the viewport is too small, this function will do nothing. - \sa setMatrix(), ensureVisible(), centerOn() + \sa setTransform(), ensureVisible(), centerOn() */ void QGraphicsView::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode) { @@ -2050,7 +1897,12 @@ void QGraphicsView::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRati void QGraphicsView::fitInView(const QGraphicsItem *item, Qt::AspectRatioMode aspectRatioMode) { QPainterPath path = item->isClipped() ? item->clipPath() : item->shape(); - fitInView(item->sceneTransform().map(path).boundingRect(), aspectRatioMode); + if (item->d_ptr->hasTranslateOnlySceneTransform()) { + path.translate(item->d_ptr->sceneTransform.dx(), item->d_ptr->sceneTransform.dy()); + fitInView(path.boundingRect(), aspectRatioMode); + } else { + fitInView(item->d_ptr->sceneTransform.map(path).boundingRect(), aspectRatioMode); + } } /*! @@ -2076,6 +1928,8 @@ void QGraphicsView::fitInView(const QGraphicsItem *item, Qt::AspectRatioMode asp void QGraphicsView::render(QPainter *painter, const QRectF &target, const QRect &source, Qt::AspectRatioMode aspectRatioMode) { + // ### Switch to using the recursive rendering algorithm instead. + Q_D(QGraphicsView); if (!d->scene || !(painter && painter->isActive())) return; @@ -2122,48 +1976,17 @@ void QGraphicsView::render(QPainter *painter, const QRectF &target, const QRect itemList.clear(); // Setup painter matrix. - QTransform moveMatrix; - moveMatrix.translate(-d->horizontalScroll(), -d->verticalScroll()); + QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll()); QTransform painterMatrix = d->matrix * moveMatrix; painterMatrix *= QTransform() .translate(targetRect.left(), targetRect.top()) .scale(xratio, yratio) .translate(-sourceRect.left(), -sourceRect.top()); - // Two unit vectors. - QLineF v1(0, 0, 1, 0); - QLineF v2(0, 0, 0, 1); - // Generate the style options QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems); - QStyleOptionGraphicsItem* option = styleOptionArray; - for (int i = 0; i < numItems; ++i, ++option) { - QGraphicsItem *item = itemArray[i]; - - option->state = QStyle::State_None; - option->rect = item->boundingRect().toRect(); - if (item->isSelected()) - option->state |= QStyle::State_Selected; - if (item->isEnabled()) - option->state |= QStyle::State_Enabled; - if (item->hasFocus()) - option->state |= QStyle::State_HasFocus; - if (d->scene->d_func()->hoverItems.contains(item)) - option->state |= QStyle::State_MouseOver; - if (item == d->scene->mouseGrabberItem()) - option->state |= QStyle::State_Sunken; - - // Calculate a simple level-of-detail metric. - // ### almost identical code in QGraphicsScene::render() - // and QGraphicsView::paintEvent() - consider refactoring - QTransform itemToViewportTransform = item->deviceTransform(painterMatrix); - - option->levelOfDetail = qSqrt(itemToViewportTransform.map(v1).length() * itemToViewportTransform.map(v2).length()); - option->matrix = itemToViewportTransform.toAffine(); - - option->exposedRect = item->boundingRect(); - option->exposedRect &= itemToViewportTransform.inverted().mapRect(targetRect); - } + for (int i = 0; i < numItems; ++i) + itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterMatrix, targetRect.toRect()); painter->save(); @@ -2203,69 +2026,6 @@ QList<QGraphicsItem *> QGraphicsView::items() const } /*! - Returns all items in the area \a path, which is in viewport coordinates, - also taking untransformable items into consideration. This function is - considerably slower than just checking the scene directly. There is - certainly room for improvement. -*/ -QList<QGraphicsItem *> QGraphicsViewPrivate::itemsInArea(const QPainterPath &path, - Qt::ItemSelectionMode mode, - Qt::SortOrder order) const -{ - Q_Q(const QGraphicsView); - - // Determine the size of the largest untransformable subtree of children - // mapped to scene coordinates. - QRectF untr = scene->d_func()->largestUntransformableItem; - QRectF ltri = matrix.inverted().mapRect(untr); - ltri.adjust(-untr.width(), -untr.height(), untr.width(), untr.height()); - - QRectF rect = path.controlPointRect(); - - // Find all possible items in the relevant area. - // ### Improve this algorithm; it might be searching a too large area. - QRectF adjustedRect = q->mapToScene(rect.adjusted(-1, -1, 1, 1).toRect()).boundingRect(); - adjustedRect.adjust(-ltri.width(), -ltri.height(), ltri.width(), ltri.height()); - - // First build a (potentially large) list of all items in the vicinity - // that might be untransformable. - QList<QGraphicsItem *> allCandidates = scene->d_func()->estimateItemsInRect(adjustedRect); - - // Then find the minimal list of items that are inside \a path, and - // convert it to a set. - QList<QGraphicsItem *> regularCandidates = scene->items(q->mapToScene(path), mode); - QSet<QGraphicsItem *> candSet = QSet<QGraphicsItem *>::fromList(regularCandidates); - - QTransform viewMatrix = q->viewportTransform(); - - QList<QGraphicsItem *> result; - - // Run through all candidates and keep all items that are in candSet, or - // are untransformable and collide with \a path. ### We can improve this - // algorithm. - QList<QGraphicsItem *>::Iterator it = allCandidates.begin(); - while (it != allCandidates.end()) { - QGraphicsItem *item = *it; - if (item->d_ptr->itemIsUntransformable()) { - // Check if this untransformable item collides with the - // original selection rect. - QTransform itemTransform = item->deviceTransform(viewMatrix); - if (QGraphicsScenePrivate::itemCollidesWithPath(item, itemTransform.inverted().map(path), mode)) - result << item; - } else { - if (candSet.contains(item)) - result << item; - } - ++it; - } - - // ### Insertion sort would be faster. - if (order != Qt::SortOrder(-1)) - QGraphicsScenePrivate::sortItems(&result, order, scene->d_func()->sortCacheEnabled); - return result; -} - -/*! Returns a list of all the items at the position \a pos in the view. The items are listed in descending Z order (i.e., the first item in the list is the top-most item, and the last item is the bottom-most item). \a pos @@ -2284,17 +2044,22 @@ QList<QGraphicsItem *> QGraphicsView::items(const QPoint &pos) const Q_D(const QGraphicsView); if (!d->scene) return QList<QGraphicsItem *>(); - if (d->scene->d_func()->largestUntransformableItem.isNull()) { - if ((d->identityMatrix || d->matrix.type() <= QTransform::TxScale)) { - QTransform xinv = viewportTransform().inverted(); - return d->scene->items(xinv.mapRect(QRectF(pos.x(), pos.y(), 1, 1))); - } - return d->scene->items(mapToScene(pos.x(), pos.y(), 2, 2)); + // ### Unify these two, and use the items(QPointF) version in + // QGraphicsScene instead. The scene items function could use the viewport + // transform to map the point to a rect/polygon. + if ((d->identityMatrix || d->matrix.type() <= QTransform::TxScale)) { + // Use the rect version + QTransform xinv = viewportTransform().inverted(); + return d->scene->items(xinv.mapRect(QRectF(pos.x(), pos.y(), 1, 1)), + Qt::IntersectsItemShape, + Qt::AscendingOrder, + viewportTransform()); } - - QPainterPath path; - path.addRect(QRectF(pos.x(), pos.y(), 1, 1)); - return d->itemsInArea(path); + // Use the polygon version + return d->scene->items(mapToScene(pos.x(), pos.y(), 1, 1), + Qt::IntersectsItemShape, + Qt::AscendingOrder, + viewportTransform()); } /*! @@ -2321,12 +2086,7 @@ QList<QGraphicsItem *> QGraphicsView::items(const QRect &rect, Qt::ItemSelection Q_D(const QGraphicsView); if (!d->scene) return QList<QGraphicsItem *>(); - if (d->scene->d_func()->largestUntransformableItem.isNull()) - return d->scene->items(mapToScene(rect), mode); - - QPainterPath path; - path.addRect(rect); - return d->itemsInArea(path); + return d->scene->items(mapToScene(rect), mode, Qt::AscendingOrder, viewportTransform()); } /*! @@ -2354,13 +2114,7 @@ QList<QGraphicsItem *> QGraphicsView::items(const QPolygon &polygon, Qt::ItemSel Q_D(const QGraphicsView); if (!d->scene) return QList<QGraphicsItem *>(); - if (d->scene->d_func()->largestUntransformableItem.isNull()) - return d->scene->items(mapToScene(polygon), mode); - - QPainterPath path; - path.addPolygon(polygon); - path.closeSubpath(); - return d->itemsInArea(path); + return d->scene->items(mapToScene(polygon), mode, Qt::AscendingOrder, viewportTransform()); } /*! @@ -2380,9 +2134,7 @@ QList<QGraphicsItem *> QGraphicsView::items(const QPainterPath &path, Qt::ItemSe Q_D(const QGraphicsView); if (!d->scene) return QList<QGraphicsItem *>(); - if (d->scene->d_func()->largestUntransformableItem.isNull()) - return d->scene->items(mapToScene(path), mode); - return d->itemsInArea(path); + return d->scene->items(mapToScene(path), mode, Qt::AscendingOrder, viewportTransform()); } /*! @@ -2451,13 +2203,13 @@ QPolygonF QGraphicsView::mapToScene(const QRect &rect) const return QPolygonF(); QPointF scrollOffset(d->horizontalScroll(), d->verticalScroll()); - QPointF tl = scrollOffset + rect.topLeft(); - QPointF tr = scrollOffset + rect.topRight(); - QPointF br = scrollOffset + rect.bottomRight(); - QPointF bl = scrollOffset + rect.bottomLeft(); + QRect r = rect.adjusted(0, 0, 1, 1); + QPointF tl = scrollOffset + r.topLeft(); + QPointF tr = scrollOffset + r.topRight(); + QPointF br = scrollOffset + r.bottomRight(); + QPointF bl = scrollOffset + r.bottomLeft(); - QPolygonF poly; - poly.resize(4); + QPolygonF poly(4); if (!d->identityMatrix) { QTransform x = d->matrix.inverted(); poly[0] = x.map(tl); @@ -2503,9 +2255,9 @@ QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const QPainterPath QGraphicsView::mapToScene(const QPainterPath &path) const { Q_D(const QGraphicsView); - QTransform moveMatrix; - moveMatrix.translate(d->horizontalScroll(), d->verticalScroll()); - return (moveMatrix * d->matrix.inverted()).map(path); + QTransform matrix = QTransform::fromTranslate(d->horizontalScroll(), d->verticalScroll()); + matrix *= d->matrix.inverted(); + return matrix.map(path); } /*! @@ -2560,8 +2312,7 @@ QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const br -= scrollOffset; bl -= scrollOffset; - QPolygon poly; - poly.resize(4); + QPolygon poly(4); poly[0] = tl.toPoint(); poly[1] = tr.toPoint(); poly[2] = br.toPoint(); @@ -2599,9 +2350,9 @@ QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const QPainterPath QGraphicsView::mapFromScene(const QPainterPath &path) const { Q_D(const QGraphicsView); - QTransform moveMatrix; - moveMatrix.translate(-d->horizontalScroll(), -d->verticalScroll()); - return (d->matrix * moveMatrix).map(path); + QTransform matrix = d->matrix; + matrix *= QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll()); + return matrix.map(path); } /*! @@ -2647,7 +2398,7 @@ void QGraphicsView::setBackgroundBrush(const QBrush &brush) { Q_D(QGraphicsView); d->backgroundBrush = brush; - viewport()->update(); + d->updateAll(); if (d->cacheMode & CacheBackground) { // Invalidate the background pixmap @@ -2677,7 +2428,7 @@ void QGraphicsView::setForegroundBrush(const QBrush &brush) { Q_D(QGraphicsView); d->foregroundBrush = brush; - viewport()->update(); + d->updateAll(); } /*! @@ -2698,9 +2449,11 @@ void QGraphicsView::updateScene(const QList<QRectF> &rects) // Extract and reset dirty scene rect info. QVector<QRect> dirtyViewportRects; - for (int i = 0; i < d->dirtyRegions.size(); ++i) - dirtyViewportRects += d->dirtyRegions.at(i).rects(); - d->dirtyRegions.clear(); + const QVector<QRect> &dirtyRects = d->dirtyRegion.rects(); + for (int i = 0; i < dirtyRects.size(); ++i) + dirtyViewportRects += dirtyRects.at(i); + d->dirtyRegion = QRegion(); + d->dirtyBoundingRect = QRect(); bool fullUpdate = !d->accelerateScrolling || d->viewportUpdateMode == QGraphicsView::FullViewportUpdate; bool boundingRectUpdate = (d->viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) @@ -2784,9 +2537,7 @@ void QGraphicsView::setupViewport(QWidget *widget) const bool isGLWidget = widget->inherits("QGLWidget"); - d->accelerateScrolling = !(isGLWidget - || widget->testAttribute(Qt::WA_MSWindowsUseDirect3D) - || qApp->testAttribute(Qt::AA_MSWindowsUseDirect3DByDefault)); + d->accelerateScrolling = !(isGLWidget); widget->setFocusPolicy(Qt::StrongFocus); @@ -2795,7 +2546,17 @@ void QGraphicsView::setupViewport(QWidget *widget) widget->setAutoFillBackground(true); } - widget->setMouseTracking(true); + // We are only interested in mouse tracking if items + // accept hover events or use non-default cursors. + if (d->scene && (!d->scene->d_func()->allItemsIgnoreHoverEvents + || !d->scene->d_func()->allItemsUseDefaultCursor)) { + widget->setMouseTracking(true); + } + + // enable touch events if any items is interested in them + if (d->scene && !d->scene->d_func()->allItemsIgnoreTouchEvents) + widget->setAttribute(Qt::WA_AcceptTouchEvents); + widget->setAcceptDrops(acceptDrops()); } @@ -2894,6 +2655,7 @@ bool QGraphicsView::viewportEvent(QEvent *event) case QEvent::Paint: // Reset full update d->fullUpdatePending = false; + d->dirtyScrollOffset = QPoint(); if (d->scene) { // Check if this view reimplements the updateScene slot; if it // does, we can't do direct update delivery and have to fall back @@ -2912,6 +2674,23 @@ bool QGraphicsView::viewportEvent(QEvent *event) d->scene->d_func()->updateAll = false; } break; + case QEvent::TouchBegin: + case QEvent::TouchUpdate: + case QEvent::TouchEnd: + { + if (!isEnabled()) + return false; + + if (d->scene && d->sceneInteractionAllowed) { + // Convert and deliver the touch event to the scene. + QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event); + touchEvent->setWidget(viewport()); + QGraphicsViewPrivate::translateTouchEvent(d, touchEvent); + (void) QApplication::sendEvent(d->scene, touchEvent); + } + + return true; + } default: break; } @@ -3085,6 +2864,7 @@ void QGraphicsView::dragMoveEvent(QDragMoveEvent *event) void QGraphicsView::focusInEvent(QFocusEvent *event) { Q_D(QGraphicsView); + d->updateInputMethodSensitivity(); QAbstractScrollArea::focusInEvent(event); if (d->scene) QApplication::sendEvent(d->scene, event); @@ -3170,7 +2950,10 @@ void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event) mouseEvent.setAccepted(false); mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); } /*! @@ -3209,7 +2992,10 @@ void QGraphicsView::mousePressEvent(QMouseEvent *event) mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); mouseEvent.setAccepted(false); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); // Update the original mouse event accepted state. bool isAccepted = mouseEvent.isAccepted(); @@ -3270,7 +3056,7 @@ void QGraphicsView::mouseMoveEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } // Stop rubber banding if the user has let go of all buttons (even @@ -3292,14 +3078,15 @@ void QGraphicsView::mouseMoveEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } // Set the new selection area QPainterPath selectionArea; selectionArea.addPolygon(mapToScene(d->rubberBandRect)); selectionArea.closeSubpath(); if (d->scene) - d->scene->setSelectionArea(selectionArea, d->rubberBandSelectionMode); + d->scene->setSelectionArea(selectionArea, d->rubberBandSelectionMode, + viewportTransform()); return; } } else @@ -3335,7 +3122,7 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } d->rubberBanding = false; d->rubberBandRect = QRect(); @@ -3379,7 +3166,10 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event) mouseEvent.setButton(event->button()); mouseEvent.setModifiers(event->modifiers()); mouseEvent.setAccepted(false); - QApplication::sendEvent(d->scene, &mouseEvent); + if (event->spontaneous()) + qt_sendSpontaneousEvent(d->scene, &mouseEvent); + else + QApplication::sendEvent(d->scene, &mouseEvent); // Update the last mouse event selected state. d->lastMouseEvent.setAccepted(mouseEvent.isAccepted()); @@ -3437,16 +3227,11 @@ void QGraphicsView::paintEvent(QPaintEvent *event) d->scene->d_func()->painterStateProtection = !(d->optimizationFlags & DontSavePainterState); // Determine the exposed region - QRegion exposedRegion = event->region(); - if (!d->accelerateScrolling) - exposedRegion = viewport()->rect(); - else if (d->viewportUpdateMode == BoundingRectViewportUpdate) - exposedRegion = event->rect(); - QRectF exposedSceneRect = mapToScene(exposedRegion.boundingRect().adjusted(0, 0, 1, 1)).boundingRect(); + d->exposedRegion = event->region(); + QRectF exposedSceneRect = mapToScene(d->exposedRegion.boundingRect()).boundingRect(); // Set up the painter QPainter painter(viewport()); - QTransform original = painter.worldTransform(); #ifndef QT_NO_RUBBERBAND if (d->rubberBanding && !d->rubberBandRect.isEmpty()) painter.save(); @@ -3456,23 +3241,12 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.setRenderHints(d->renderHints, true); // Set up viewport transform - const QTransform viewTransform = viewportTransform(); - painter.setTransform(viewTransform, true); - -#ifdef QGRAPHICSVIEW_DEBUG - QTime stopWatch; - stopWatch.start(); - qDebug() << "QGraphicsView::paintEvent(" << exposedRegion << ")"; -#endif - - // Find all exposed items - bool allItems = false; - QList<QGraphicsItem *> itemList = d->findItems(exposedRegion, &allItems); - -#ifdef QGRAPHICSVIEW_DEBUG - int exposedTime = stopWatch.elapsed(); -#endif + const bool viewTransformed = isTransformed(); + if (viewTransformed) + painter.setWorldTransform(viewportTransform()); + const QTransform viewTransform = painter.worldTransform(); + // Draw background if ((d->cacheMode & CacheBackground) #ifdef Q_WS_X11 && X11->use_xrender @@ -3495,16 +3269,21 @@ void QGraphicsView::paintEvent(QPaintEvent *event) if (!d->backgroundPixmapExposed.isEmpty()) { QPainter backgroundPainter(&d->backgroundPixmap); backgroundPainter.setClipRegion(d->backgroundPixmapExposed, Qt::ReplaceClip); - backgroundPainter.setTransform(viewportTransform()); + if (viewTransformed) + backgroundPainter.setTransform(viewTransform); + backgroundPainter.setCompositionMode(QPainter::CompositionMode_Source); drawBackground(&backgroundPainter, exposedSceneRect); d->backgroundPixmapExposed = QRegion(); } // Blit the background from the background pixmap - QTransform oldMatrix = painter.worldTransform(); - painter.setWorldTransform(original); - painter.drawPixmap(QPoint(), d->backgroundPixmap); - painter.setWorldTransform(oldMatrix); + if (viewTransformed) { + painter.setWorldTransform(QTransform()); + painter.drawPixmap(QPoint(), d->backgroundPixmap); + painter.setWorldTransform(viewTransform); + } else { + painter.drawPixmap(QPoint(), d->backgroundPixmap); + } } else { if (!(d->optimizationFlags & DontSavePainterState)) painter.save(); @@ -3513,34 +3292,32 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.restore(); } -#ifdef QGRAPHICSVIEW_DEBUG - int backgroundTime = stopWatch.elapsed() - exposedTime; -#endif - - // Generate the style options - QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()]; - QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(itemList.size()); - - d->generateStyleOptions(itemList, itemArray, styleOptionArray, viewTransform, - allItems, exposedRegion); - // Items - drawItems(&painter, itemList.size(), itemArray, styleOptionArray); - -#ifdef QGRAPHICSVIEW_DEBUG - int itemsTime = stopWatch.elapsed() - exposedTime - backgroundTime; -#endif + if (!(d->optimizationFlags & IndirectPainting)) { + d->scene->d_func()->drawItems(&painter, viewTransformed ? &viewTransform : 0, + &d->exposedRegion, viewport()); + } else { + // Find all exposed items + bool allItems = false; + QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems, viewTransform); + if (!itemList.isEmpty()) { + // Generate the style options. + const int numItems = itemList.size(); + QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid. + QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems); + for (int i = 0; i < numItems; ++i) { + itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], viewTransform, + d->exposedRegion, allItems); + } + // Draw the items. + drawItems(&painter, numItems, itemArray, styleOptionArray); + d->freeStyleOptionsArray(styleOptionArray); + } + } // Foreground drawForeground(&painter, exposedSceneRect); - delete [] itemArray; - d->freeStyleOptionsArray(styleOptionArray); - -#ifdef QGRAPHICSVIEW_DEBUG - int foregroundTime = stopWatch.elapsed() - exposedTime - backgroundTime - itemsTime; -#endif - #ifndef QT_NO_RUBBERBAND // Rubberband if (d->rubberBanding && !d->rubberBandRect.isEmpty()) { @@ -3562,17 +3339,6 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.end(); -#ifdef QGRAPHICSVIEW_DEBUG - qDebug() << "\tItem discovery....... " << exposedTime << "msecs (" << itemList.size() << "items," - << (exposedTime > 0 ? (itemList.size() * 1000.0 / exposedTime) : -1) << "/ sec )"; - qDebug() << "\tDrawing background... " << backgroundTime << "msecs (" << exposedRegion.numRects() << "segments )"; - qDebug() << "\tDrawing items........ " << itemsTime << "msecs (" - << (itemsTime > 0 ? (itemList.size() * 1000.0 / itemsTime) : -1) << "/ sec )"; - qDebug() << "\tDrawing foreground... " << foregroundTime << "msecs (" << exposedRegion.numRects() << "segments )"; - qDebug() << "\tTotal rendering time: " << stopWatch.elapsed() << "msecs (" - << (stopWatch.elapsed() > 0 ? (1000.0 / stopWatch.elapsed()) : -1.0) << "fps )"; -#endif - // Restore painter state protection. d->scene->d_func()->painterStateProtection = true; } @@ -3619,10 +3385,6 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate) { if (d->viewportUpdateMode != QGraphicsView::FullViewportUpdate) { - for (int i = 0; i < d->dirtyRects.size(); ++i) - d->dirtyRects[i].translate(dx, dy); - for (int i = 0; i < d->dirtyRegions.size(); ++i) - d->dirtyRegions[i].translate(dx, dy); if (d->accelerateScrolling) { #ifndef QT_NO_RUBBERBAND // Update new and old rubberband regions @@ -3632,12 +3394,15 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) viewport()->update(rubberBandRegion); } #endif + d->dirtyScrollOffset.rx() += dx; + d->dirtyScrollOffset.ry() += dy; + d->dirtyRegion.translate(dx, dy); viewport()->scroll(dx, dy); } else { - viewport()->update(); + d->updateAll(); } } else { - viewport()->update(); + d->updateAll(); } } @@ -3648,31 +3413,14 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) && X11->use_xrender #endif ) { - // Invalidate the background pixmap - d->backgroundPixmapExposed.translate(dx, 0); - if (dx > 0) { - d->backgroundPixmapExposed += QRect(0, 0, dx, viewport()->height()); - } else if (dx < 0) { - d->backgroundPixmapExposed += QRect(viewport()->width() + dx, 0, - -dx, viewport()->height()); - } - d->backgroundPixmapExposed.translate(0, dy); - if (dy > 0) { - d->backgroundPixmapExposed += QRect(0, 0, viewport()->width(), dy); - } else if (dy < 0) { - d->backgroundPixmapExposed += QRect(0, viewport()->height() + dy, - viewport()->width(), -dy); - } - // Scroll the background pixmap - if (!d->backgroundPixmap.isNull()) { - QPixmap tmp = d->backgroundPixmap.copy(); - QBrush bgBrush = viewport()->palette().brush(viewport()->backgroundRole()); - if (!bgBrush.isOpaque()) - d->backgroundPixmap.fill(Qt::transparent); - QPainter painter(&d->backgroundPixmap); - painter.drawPixmap(dx, dy, tmp); - } + QRegion exposed; + if (!d->backgroundPixmap.isNull()) + d->backgroundPixmap.scroll(dx, dy, d->backgroundPixmap.rect(), &exposed); + + // Invalidate the background pixmap + d->backgroundPixmapExposed.translate(dx, dy); + d->backgroundPixmapExposed += exposed; } // Always replay on scroll. @@ -3773,8 +3521,10 @@ void QGraphicsView::drawItems(QPainter *painter, int numItems, const QStyleOptionGraphicsItem options[]) { Q_D(QGraphicsView); - if (d->scene) - d->scene->drawItems(painter, numItems, items, options, viewport()); + if (d->scene) { + QWidget *widget = painter->device() == viewport() ? viewport() : 0; + d->scene->drawItems(painter, numItems, items, options, widget); + } } /*! @@ -3797,12 +3547,25 @@ QTransform QGraphicsView::transform() const QTransform QGraphicsView::viewportTransform() const { Q_D(const QGraphicsView); - QTransform moveMatrix; - moveMatrix.translate(-d->horizontalScroll(), -d->verticalScroll()); + QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll()); return d->identityMatrix ? moveMatrix : d->matrix * moveMatrix; } /*! + \since 4.6 + + Returns true if the view is transformed (i.e., a non-identity transform + has been assigned, or the scrollbars are adjusted). + + \sa setTransform(), horizontalScrollBar(), verticalScrollBar() +*/ +bool QGraphicsView::isTransformed() const +{ + Q_D(const QGraphicsView); + return !d->identityMatrix || d->horizontalScroll() || d->verticalScroll(); +} + +/*! Sets the view's current transformation matrix to \a matrix. If \a combine is true, then \a matrix is combined with the current matrix; @@ -3853,7 +3616,7 @@ void QGraphicsView::setTransform(const QTransform &matrix, bool combine ) d->transforming = false; // Any matrix operation requires a full update. - viewport()->update(); + d->updateAll(); } /*! @@ -3866,6 +3629,38 @@ void QGraphicsView::resetTransform() setTransform(QTransform()); } +QPointF QGraphicsViewPrivate::mapToScene(const QPointF &point) const +{ + QPointF p = point; + p.rx() += horizontalScroll(); + p.ry() += verticalScroll(); + return identityMatrix ? p : matrix.inverted().map(p); +} + +QRectF QGraphicsViewPrivate::mapToScene(const QRectF &rect) const +{ + QPointF scrollOffset(horizontalScroll(), verticalScroll()); + QPointF tl = scrollOffset + rect.topLeft(); + QPointF tr = scrollOffset + rect.topRight(); + QPointF br = scrollOffset + rect.bottomRight(); + QPointF bl = scrollOffset + rect.bottomLeft(); + + QPolygonF poly(4); + if (!identityMatrix) { + QTransform x = matrix.inverted(); + poly[0] = x.map(tl); + poly[1] = x.map(tr); + poly[2] = x.map(br); + poly[3] = x.map(bl); + } else { + poly[0] = tl; + poly[1] = tr; + poly[2] = br; + poly[3] = bl; + } + return poly.boundingRect(); +} + QT_END_NAMESPACE #include "moc_qgraphicsview.cpp" |