diff options
author | Bradley T. Hughes <bradley.hughes@nokia.com> | 2009-06-10 15:08:15 (GMT) |
---|---|---|
committer | Bradley T. Hughes <bradley.hughes@nokia.com> | 2009-06-10 15:08:15 (GMT) |
commit | d8f65a7f0707d8a97801ad20d690672e0124b491 (patch) | |
tree | 0c881ac70d9063044ca1ca09290d0747bf322693 /src/gui/graphicsview | |
parent | 9683cf068c3f933f836dc2a5b4a19b1c2f86d38a (diff) | |
parent | 747444c6776d948dad479e7b6f3564d0515d4e52 (diff) | |
download | Qt-d8f65a7f0707d8a97801ad20d690672e0124b491.zip Qt-d8f65a7f0707d8a97801ad20d690672e0124b491.tar.gz Qt-d8f65a7f0707d8a97801ad20d690672e0124b491.tar.bz2 |
Merge branch 'master' of git@scm.dev.nokia.troll.no:qt/qt
Conflicts:
src/gui/graphicsview/qgraphicsitem.cpp
src/gui/graphicsview/qgraphicsitem_p.h
src/gui/graphicsview/qgraphicsscene_p.h
Diffstat (limited to 'src/gui/graphicsview')
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem.cpp | 1152 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem.h | 4 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsitem_p.h | 243 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsscene.cpp | 988 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsscene.h | 5 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsscene_p.h | 45 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsview.cpp | 296 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsview.h | 5 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicsview_p.h | 10 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicswidget.cpp | 3 | ||||
-rw-r--r-- | src/gui/graphicsview/qgraphicswidget_p.cpp | 2 |
11 files changed, 1400 insertions, 1353 deletions
diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 00f1aed..97ca88e 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -133,12 +133,8 @@ \section1 Transformation QGraphicsItem supports affine transformations in addition to its base - position, pos(). To change the item's transformation, you can either pass - a transformation matrix to setTransform(), or set the different transformation - properties (transformOrigin, x/y/zRotation, x/yScale, horizontal/verticalShear). - Note that setting the transformation matrix conflicts with using the properties. - Setting the properties will overwrite the transformation set with setTransform, - and using setTransform will reset the properties. + position, pos(). To change the item's transformation, you can pass + a transformation matrix to setTransform() Item transformations accumulate from parent to child, so if both a parent and child item are rotated 90 degrees, the child's total transformation will be 180 degrees. @@ -152,19 +148,18 @@ and scenePos(), which returns its position in scene coordinates. To reset an item's matrix, call resetTransform(). + Another way to apply transformation to an item is to use the , or set the + different transformation properties (transformOrigin, x/y/zRotation, x/yScale, + horizontal/verticalShear). Those properties come in addition to the base transformation + The order you set the transformation properties does not affect the resulting transformation The resulting transformation is always computed in the following order \code - [Origin] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] + [Origin] [Base] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] \endcode - So the transformation is equivalent to the following code - - \code - QTransform().translate(xOrigin, yOrigin).rotate(xRotation, Qt::XAxis).rotate(yRotation, Qt::YAxis).rotate(zRotation, Qt::ZAxis) - .shear(horizontalShear, verticalShear).scale(xScale, yScale).translate(-xOrigin, -yOrigin); - \endcode + Where [Base] is the stransformation set by setTransform \section1 Painting @@ -309,6 +304,18 @@ and is always initialized to 1. Use QStyleOptionGraphicsItem::levelOfDetailFromTransform for a more fine-grained value. + + \value ItemHasNoContents The item does not paint anything (i.e., calling + paint() on the item has no effect). You should set this flag on items that + do not need to be painted to ensure that Graphics View avoids unnecessary + painting preparations. This flag was introduced in Qt 4.6. + + \value ItemSendsGeometryChanges The item enables itemChange() + notifications for ItemPositionChange, ItemPositionHasChanged, + ItemMatrixChange, ItemTransformChange, and ItemTransformHasChanged. For + performance reasons, these notifications are disabled by default. You must + enable this flag to receive notifications for position and transform + changes. This flag was introduced in Qt 4.6. */ /*! @@ -347,33 +354,36 @@ changing. This value is obsolete; you can use ItemTransformChange instead. \value ItemPositionChange The item's position changes. This notification - is only sent when the item's local position changes, relative to its - parent, has changed (i.e., as a result of calling setPos() or - moveBy()). The value argument is the new position (i.e., a QPointF). You - can call pos() to get the original position. Do not call setPos() or - moveBy() in itemChange() as this notification is delivered; instead, you - can return the new, adjusted position from itemChange(). After this - notification, QGraphicsItem immediately sends the ItemPositionHasChanged - notification if the position changed. + is sent if the ItemSendsGeometryChanges flag is enabled, and when the + item's local position changes, relative to its parent (i.e., as a result + of calling setPos() or moveBy()). The value argument is the new position + (i.e., a QPointF). You can call pos() to get the original position. Do + not call setPos() or moveBy() in itemChange() as this notification is + delivered; instead, you can return the new, adjusted position from + itemChange(). After this notification, QGraphicsItem immediately sends the + ItemPositionHasChanged notification if the position changed. \value ItemPositionHasChanged The item's position has changed. This - notification is only sent after the item's local position, relative to its - parent, has changed. The value argument is the new position (the same as - pos()), and QGraphicsItem ignores the return value for this notification - (i.e., a read-only notification). + notification is sent if the ItemSendsGeometryChanges flag is enabled, and + after the item's local position, relative to its parent, has changed. The + value argument is the new position (the same as pos()), and QGraphicsItem + ignores the return value for this notification (i.e., a read-only + notification). \value ItemTransformChange The item's transformation matrix changes. This - notification is only sent when the item's local transformation matrix - changes (i.e., as a result of calling setTransform(). The value - argument is the new matrix (i.e., a QTransform); to get the old matrix, - call transform(). Do not call setTransform() or set any of the transformation - properties in itemChange() as this notification is delivered; - instead, you can return the new matrix from itemChange(). - This notification is not sent if you change the transformation properties. + notification is send if the ItemSendsGeometryChanges flag is enabled, and + when the item's local transformation matrix changes (i.e., as a result of + calling setTransform(). The value argument is the new matrix (i.e., a + QTransform); to get the old matrix, call transform(). Do not call + setTransform() or set any of the transformation properties in itemChange() + as this notification is delivered; instead, you can return the new matrix + from itemChange(). This notification is not sent if you change the + transformation properties. \value ItemTransformHasChanged The item's transformation matrix has - changed either because setTransform is called, or one of the transformation - properties is changed. This notification is only sent after the item's local + changed either because setTransform is called, or one of the + transformation properties is changed. This notification is sent if the + ItemSendsGeometryChanges flag is enabled, and after the item's local transformation matrix has changed. The value argument is the new matrix (same as transform()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). @@ -775,12 +785,43 @@ QPointF QGraphicsItemPrivate::genericMapFromScene(const QPointF &pos, /*! \internal - Returns true if this item or any of its ancestors are untransformable. + Combines this item's position and transform onto \a transform. + + If you need to change this function (e.g., adding more transformation + modes / options), make sure to change all places marked with COMBINE. +*/ +void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransform *viewTransform) const +{ + // COMBINE + if (itemIsUntransformable() && viewTransform) { + *x = q_ptr->deviceTransform(*viewTransform); + } else { + if (transformData) + *x *= transformData->computedFullTransform(); + if (!pos.isNull()) + *x *= QTransform::fromTranslate(pos.x(), pos.y()); + } +} + +/*! + \internal + + Combines this item's position and transform onto \a transform. + + If you need to change this function (e.g., adding more transformation + modes / options), make sure to change QGraphicsItem::deviceTransform() as + well. */ -bool QGraphicsItemPrivate::itemIsUntransformable() const +void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTransform *viewTransform) const { - return (flags & QGraphicsItem::ItemIgnoresTransformations) - || (ancestorFlags & AncestorIgnoresTransformations); + // COMBINE + if (itemIsUntransformable() && viewTransform) { + *x = q_ptr->deviceTransform(*viewTransform); + } else { + x->translate(pos.x(), pos.y()); + if (transformData) + *x = transformData->computedFullTransform() * *x; + } } /*! @@ -802,11 +843,11 @@ QVariant QGraphicsItemPrivate::inputMethodQueryHelper(Qt::InputMethodQuery query /*! \internal - If \a deleting is true, then this item is being deleted, and \a parent is - null. Make sure not to trigger any pure virtual function calls (e.g., - prepareGeometryChange). + Make sure not to trigger any pure virtual function calls (e.g., + prepareGeometryChange) if the item is in its destructor, i.e. + inDestructor is 1. */ -void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool deleting) +void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent) { Q_Q(QGraphicsItem); if (newParent == q) { @@ -833,7 +874,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // We anticipate geometry changes. If the item is deleted, it will be // removed from the index at a later stage, and the whole scene will be // updated. - if (!deleting) + if (!inDestructor) q_ptr->prepareGeometryChange(); const QVariant thisPointerVariant(qVariantFromValue<QGraphicsItem *>(q)); @@ -845,7 +886,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // Update toplevelitem list. If this item is being deleted, its parent // will be 0 but we don't want to register/unregister it in the TLI list. - if (scene && !deleting) { + if (scene && !inDestructor) { if (parent && !newParent) { scene->d_func()->registerTopLevelItem(q); } else if (!parent && newParent) { @@ -866,8 +907,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de parent->d_ptr->addChild(q); parent->itemChange(QGraphicsItem::ItemChildAddedChange, thisPointerVariant); - if (!implicitUpdate) - updateHelper(QRectF(), false, true); + if (!implicitUpdate && scene) { + scene->d_func()->markDirty(q_ptr, QRect(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/true); + } // Inherit ancestor flags from the new parent. updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-1)); @@ -890,7 +934,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de updateAncestorFlag(QGraphicsItem::ItemClipsChildrenToShape); updateAncestorFlag(QGraphicsItem::ItemIgnoresTransformations); - if (!deleting) { + if (!inDestructor) { // Update item visible / enabled. if (!visible && !explicitlyHidden) setVisibleHelper(true, /* explicit = */ false); @@ -898,7 +942,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de setEnabledHelper(true, /* explicit = */ false); // If the item is being deleted, the whole scene will be updated. - updateHelper(QRectF(), false, true); + if (scene) { + scene->d_func()->markDirty(q_ptr, QRect(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/true); + } } } @@ -908,14 +956,9 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de scene->d_func()->invalidateSortCache(); } - // Resolve opacity. - updateEffectiveOpacity(); - // Resolve depth. resolveDepth(parent ? parent->d_ptr->depth : -1); - - // Invalidate transform cache. - invalidateSceneTransformCache(); + dirtySceneTransform = 1; // Deliver post-change notification q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); @@ -928,20 +971,18 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de */ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rect) { + if (!dirtyChildrenBoundingRect) { + *rect |= x->mapRect(childrenBoundingRect); + return; + } + for (int i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); QGraphicsItemPrivate *childd = child->d_ptr; - bool hasX = childd->hasTransform; bool hasPos = !childd->pos.isNull(); - if (hasPos || hasX) { - QTransform matrix; - if (hasX) - matrix = child->transform(); - if (hasPos) { - const QPointF &p = childd->pos; - matrix *= QTransform::fromTranslate(p.x(), p.y()); - } - matrix *= *x; + if (hasPos || childd->transformData) { + // COMBINE + QTransform matrix = childd->transformToParent() * *x; *rect |= matrix.mapRect(child->boundingRect()); if (!childd->children.isEmpty()) childd->childrenBoundingRectHelper(&matrix, rect); @@ -951,6 +992,9 @@ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rec childd->childrenBoundingRectHelper(x, rect); } } + + childrenBoundingRect = *rect; + dirtyChildrenBoundingRect = 0; } void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform, @@ -982,14 +1026,12 @@ void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, con return; // Initialize QStyleOptionGraphicsItem specific values (matrix, exposedRect). - - const QTransform itemToViewportTransform = q->deviceTransform(worldTransform); - option->matrix = itemToViewportTransform.toAffine(); //### discards perspective + option->matrix = worldTransform.toAffine(); //### discards perspective if (!allItems) { // Determine the item's exposed area option->exposedRect = QRectF(); - const QTransform reverseMap = itemToViewportTransform.inverted(); + const QTransform reverseMap = worldTransform.inverted(); const QVector<QRect> exposedRects(exposedRegion.rects()); for (int i = 0; i < exposedRects.size(); ++i) { option->exposedRect |= reverseMap.mapRect(exposedRects.at(i)); @@ -1076,21 +1118,23 @@ QGraphicsItem::QGraphicsItem(QGraphicsItemPrivate &dd, QGraphicsItem *parent, */ QGraphicsItem::~QGraphicsItem() { - if (d_ptr->scene && !d_ptr->parent) - d_ptr->scene->d_func()->unregisterTopLevelItem(this); - - clearFocus(); - + d_ptr->inDestructor = 1; d_ptr->removeExtraItemCache(); d_ptr->removeExtraGestures(); - QList<QGraphicsItem *> oldChildren = d_ptr->children; - qDeleteAll(oldChildren); - Q_ASSERT(d_ptr->children.isEmpty()); - d_ptr->setParentItemHelper(0, /* deleting = */ true); + clearFocus(); + if (!d_ptr->children.isEmpty()) { + QList<QGraphicsItem *> oldChildren = d_ptr->children; + qDeleteAll(oldChildren); + Q_ASSERT(d_ptr->children.isEmpty()); + } + if (d_ptr->scene) - d_ptr->scene->d_func()->_q_removeItemLater(this); + d_ptr->scene->d_func()->removeItemHelper(this); + else + d_ptr->setParentItemHelper(0); + delete d_ptr->transformData; delete d_ptr; qt_dataStore()->data.remove(this); @@ -1232,7 +1276,7 @@ QGraphicsWidget *QGraphicsItem::window() const */ void QGraphicsItem::setParentItem(QGraphicsItem *parent) { - d_ptr->setParentItemHelper(parent, /* deleting = */ false); + d_ptr->setParentItemHelper(parent); } /*! @@ -1337,7 +1381,9 @@ static void _q_qgraphicsItemSetFlag(QGraphicsItem *item, QGraphicsItem::Graphics item was selected, and \a flags does not enabled ItemIsSelectable, the item is automatically unselected. - By default, no flags are enabled. + By default, no flags are enabled. (QGraphicsWidget enables the + ItemSendsGeometryChanges flag by default in order to track position + changes.) \sa flags(), setFlag() */ @@ -1354,7 +1400,7 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations); bool fullUpdate = (quint32(flags) & geomChangeFlagsMask) != (d_ptr->flags & geomChangeFlagsMask); if (fullUpdate) - d_ptr->fullUpdateHelper(false, true); + d_ptr->paintedViewBoundingRectsNeedRepaint = 1; // Keep the old flags to compare the diff. GraphicsItemFlags oldFlags = this->flags(); @@ -1362,11 +1408,6 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) // Update flags. d_ptr->flags = flags; - // Reresolve effective opacity if the opacity flags change. - static const quint32 opacityFlagsMask = ItemIgnoresParentOpacity | ItemDoesntPropagateOpacityToChildren; - if ((flags & opacityFlagsMask) != (oldFlags & opacityFlagsMask)) - d_ptr->updateEffectiveOpacity(); - if (!(d_ptr->flags & ItemIsFocusable) && hasFocus()) { // Clear focus on the item if it has focus when the focusable flag // is unset. @@ -1394,8 +1435,19 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) d_ptr->updateAncestorFlag(ItemIgnoresTransformations); } - // ### Why updateHelper? - d_ptr->updateHelper(QRectF(), false, true); + if ((flags & ItemStacksBehindParent) != (oldFlags & ItemStacksBehindParent)) { + // Ensure child item sorting is up to date when toggling this flag. + if (d_ptr->parent) + d_ptr->parent->d_ptr->needSortChildren = 1; + else if (d_ptr->scene) + d_ptr->scene->d_func()->needSortTopLevelItems = 1; + } + + if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath*/true); + } // Notify change. itemChange(ItemFlagsHaveChanged, quint32(flags)); @@ -1661,7 +1713,12 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo QGraphicsItemCache *c = (QGraphicsItemCache *)qVariantValue<void *>(extra(ExtraCacheData)); if (c) c->purge(); - updateHelper(QRectF(), /* force = */ true); + if (scene) { + scene->d_func()->markDirty(q_ptr, QRectF(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/false, + /*force=*/true); + } } // Certain properties are dropped as an item becomes invisible. @@ -1824,8 +1881,8 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo enabled = newEnabledVariant.toBool(); // Schedule redraw. - if (update) - updateHelper(); + if (update && scene) + scene->d_func()->markDirty(q_ptr); foreach (QGraphicsItem *child, children) { if (!newEnabled || !child->d_ptr->explicitlyDisabled) @@ -1926,9 +1983,8 @@ void QGraphicsItem::setSelected(bool selected) return; d_ptr->selected = newSelected; - d_ptr->updateHelper(); - if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this); QGraphicsScenePrivate *sceneD = d_ptr->scene->d_func(); if (selected) { sceneD->selectedItems << this; @@ -1964,12 +2020,7 @@ void QGraphicsItem::setSelected(bool selected) */ qreal QGraphicsItem::opacity() const { - if (d_ptr->hasOpacity) { - QVariant o = d_ptr->extra(QGraphicsItemPrivate::ExtraOpacity); - if (!o.isNull()) - return o.toDouble(); - } - return qreal(1.0); + return d_ptr->opacity; } /*! @@ -1985,11 +2036,7 @@ qreal QGraphicsItem::opacity() const */ qreal QGraphicsItem::effectiveOpacity() const { - if (!d_ptr->hasEffectiveOpacity) - return qreal(1.0); - - QVariant effectiveOpacity = d_ptr->extra(QGraphicsItemPrivate::ExtraEffectiveOpacity); - return effectiveOpacity.isNull() ? qreal(1.0) : qreal(effectiveOpacity.toDouble()); + return d_ptr->effectiveOpacity(); } /*! @@ -2024,30 +2071,21 @@ void QGraphicsItem::setOpacity(qreal opacity) newOpacity = qBound<qreal>(0.0, newOpacity, 1.0); // No change? Done. - if (qFuzzyIsNull(newOpacity - this->opacity())) + if (newOpacity == d_ptr->opacity) return; - // Assign local opacity. - if (qFuzzyIsNull(newOpacity - 1)) { - // Opaque, unset opacity. - d_ptr->hasOpacity = 0; - d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraOpacity); - } else { - d_ptr->hasOpacity = 1; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraOpacity, double(newOpacity)); - } - - // Resolve effective opacity. - if (QGraphicsItem *p = d_ptr->parent) - d_ptr->resolveEffectiveOpacity(p->effectiveOpacity()); - else - d_ptr->resolveEffectiveOpacity(1.0); + d_ptr->opacity = newOpacity; // Notify change. - itemChange(ItemOpacityHasChanged, newOpacity); + itemChange(ItemOpacityHasChanged, newOpacityVariant); // Update. - d_ptr->fullUpdateHelper(/*childrenOnly=*/false, /*maybeDirtyClipPath=*/false, /*ignoreOpacity=*/true); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath=*/false, + /*force=*/false, + /*ignoreOpacity=*/true); } /*! @@ -2503,38 +2541,33 @@ QPointF QGraphicsItem::scenePos() const /*! \internal - Sets the position \a pos and notifies the change. If \a update is true, - the item is also updated; otherwise it is not updated before and after the - change. + Sets the position \a pos. */ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) { Q_Q(QGraphicsItem); - if (this->pos == pos) - return; - - // Notify the item that the position is changing. - const QVariant newPosVariant(q->itemChange(QGraphicsItem::ItemPositionChange, pos)); - QPointF newPos = newPosVariant.toPointF(); - if (newPos == this->pos) - return; - - // Update and repositition. inSetPosHelper = 1; - updateCachedClipPathFromSetPosHelper(newPos); - if (scene) { - fullUpdateHelper(true); + updateCachedClipPathFromSetPosHelper(pos); + if (scene) q->prepareGeometryChange(); - } - this->pos = newPos; - invalidateSceneTransformCache(); - - // Send post-notification. - q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); + this->pos = pos; + dirtySceneTransform = 1; inSetPosHelper = 0; } /*! + \internal + + Sets the transform \a transform. +*/ +void QGraphicsItemPrivate::setTransformHelper(const QTransform &transform) +{ + q_ptr->prepareGeometryChange(); + transformData->transform = transform; + dirtySceneTransform = 1; +} + +/*! Sets the position of the item to \a pos, which is in parent coordinates. For items with no parent, \a pos is in scene coordinates. @@ -2546,7 +2579,26 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) */ void QGraphicsItem::setPos(const QPointF &pos) { - d_ptr->setPosHelper(pos); + if (d_ptr->pos == pos) + return; + + // Update and repositition. + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setPosHelper(pos); + return; + } + + // Notify the item that the position is changing. + const QVariant newPosVariant(itemChange(ItemPositionChange, qVariantFromValue<QPointF>(pos))); + QPointF newPos = newPosVariant.toPointF(); + if (newPos == d_ptr->pos) + return; + + // Update and repositition. + d_ptr->setPosHelper(newPos); + + // Send post-notification. + itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); } /*! @@ -2631,19 +2683,9 @@ QMatrix QGraphicsItem::matrix() const */ QTransform QGraphicsItem::transform() const { - if (!d_ptr->hasTransform) + if (!d_ptr->transformData) return QTransform(); - if (d_ptr->hasDecomposedTransform && d_ptr->dirtyTransform) { - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - QTransform x; - decomposed->generateTransform(&x); - QVariant v(x); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, v); - d_ptr->dirtyTransform = 0; - const_cast<QGraphicsItem *>(this)->itemChange(ItemTransformHasChanged, v); - return x; - } - return qVariantValue<QTransform>(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform)); + return d_ptr->transformData->transform; } /*! @@ -2653,14 +2695,15 @@ QTransform QGraphicsItem::transform() const The default is 0 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any rotation set with the setTransform() method. \sa setXRotation(), {Transformations} */ qreal QGraphicsItem::xRotation() const { - return d_ptr->decomposedTransform()->xRotation; + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->xRotation; } /*! @@ -2668,23 +2711,17 @@ qreal QGraphicsItem::xRotation() const Sets the rotation around the X axis to \a angle degrees. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any rotation set with the setTransform() method. - \sa xRotation(), {Transformations} + \sa xRotation(), setTransformOrigin(), {Transformations} */ void QGraphicsItem::setXRotation(qreal angle) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xRotation = angle; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2694,14 +2731,15 @@ void QGraphicsItem::setXRotation(qreal angle) The default is 0 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any rotation set with the setTransform() method. \sa setYRotation(), {Transformations} */ qreal QGraphicsItem::yRotation() const { - return d_ptr->decomposedTransform()->yRotation; + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->yRotation; } /*! @@ -2709,23 +2747,17 @@ qreal QGraphicsItem::yRotation() const Sets the rotation around the Y axis to \a angle degrees. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any rotation set with the setTransform() method. - \sa yRotation(), {Transformations} + \sa yRotation(), setTransformOrigin() {Transformations} */ void QGraphicsItem::setYRotation(qreal angle) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->yRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->yRotation = angle; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2735,14 +2767,15 @@ void QGraphicsItem::setYRotation(qreal angle) The default is 0 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any rotation set with the setTransform() method. \sa setZRotation(), {Transformations} */ qreal QGraphicsItem::zRotation() const { - return d_ptr->decomposedTransform()->zRotation; + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->zRotation; } /*! @@ -2750,23 +2783,17 @@ qreal QGraphicsItem::zRotation() const Sets the rotation around the Z axis to \a angle degrees. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any rotation set with the setTransform() method. - \sa zRotation(), {Transformations} + \sa zRotation(), setTransformOrigin(), {Transformations} */ void QGraphicsItem::setZRotation(qreal angle) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->zRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->zRotation = angle; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2775,13 +2802,17 @@ void QGraphicsItem::setZRotation(qreal angle) This convenience function set the rotation angles around the 3 axes to \a x, \a y and \a z. - \sa setXRotation(), setYRotation(), setZRotation() + \sa setXRotation(), setYRotation(), setZRotation(), {Transformations} */ void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) { - setXRotation(x); - setYRotation(y); - setZRotation(z); + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xRotation = x; + d_ptr->transformData->yRotation = y; + d_ptr->transformData->zRotation = z; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2791,14 +2822,15 @@ void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) The default is 1 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any scaling set with the setTransform() method. \sa setXScale(), {Transformations} */ qreal QGraphicsItem::xScale() const { - return d_ptr->decomposedTransform()->xScale; + if (!d_ptr->transformData) + return 1; + return d_ptr->transformData->xScale; } /*! @@ -2806,23 +2838,17 @@ qreal QGraphicsItem::xScale() const Sets the scale factor on the X axis to \a factor. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any scaling set with the setTransform() method. - \sa xScale(), {Transformations} + \sa xScale(), setTransformOrigin(), {Transformations} */ void QGraphicsItem::setXScale(qreal factor) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xScale = factor; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xScale = factor; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2832,14 +2858,15 @@ void QGraphicsItem::setXScale(qreal factor) The default is 1 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any scaling set with the setTransform() method. \sa setYScale(), {Transformations} */ qreal QGraphicsItem::yScale() const { - return d_ptr->decomposedTransform()->yScale; + if (!d_ptr->transformData) + return 1; + return d_ptr->transformData->yScale; } /*! @@ -2847,23 +2874,17 @@ qreal QGraphicsItem::yScale() const Sets the scale factor on the Y axis to \a factor. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any scaling set with the setTransform() method. - \sa yScale(), {Transformations} + \sa yScale(), setTransformOrigin(), {Transformations} */ void QGraphicsItem::setYScale(qreal factor) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->yScale = factor; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->yScale = factor; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2871,12 +2892,18 @@ void QGraphicsItem::setYScale(qreal factor) This convenience function set the scaling factors on X and Y axis to \a sx and \a sy. - \sa setXScale(), setYScale() + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa setXScale(), setYScale(), {Transformations} */ void QGraphicsItem::setScale(qreal sx, qreal sy) { - setXScale(sx); - setYScale(sy); + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xScale = sx; + d_ptr->transformData->yScale = sy; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2886,14 +2913,15 @@ void QGraphicsItem::setScale(qreal sx, qreal sy) The default is 0 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any shearing set with the setTransform() method. \sa setHorizontalShear(), {Transformations} */ qreal QGraphicsItem::horizontalShear() const { - return d_ptr->decomposedTransform()->horizontalShear; + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->horizontalShear; } /*! @@ -2901,23 +2929,17 @@ qreal QGraphicsItem::horizontalShear() const Sets the horizontal shear to \a shear. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any shearing set with the setTransform() method. \sa horizontalShear(), {Transformations} */ void QGraphicsItem::setHorizontalShear(qreal shear) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->horizontalShear = shear; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->horizontalShear = shear; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2927,14 +2949,15 @@ void QGraphicsItem::setHorizontalShear(qreal shear) The default is 0 - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. + \warning The value doesn't take in account any shearing set with the setTransform() method. \sa setHorizontalShear(), {Transformations} */ qreal QGraphicsItem::verticalShear() const { - return d_ptr->decomposedTransform()->verticalShear; + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->verticalShear; } /*! @@ -2942,23 +2965,17 @@ qreal QGraphicsItem::verticalShear() const Sets the vertical shear to \a shear. - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \warning The value doesn't take in account any shearing set with the setTransform() method. \sa verticalShear(), {Transformations} */ void QGraphicsItem::setVerticalShear(qreal shear) { - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->verticalShear = shear; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->verticalShear = shear; + d_ptr->dirtySceneTransform = 1; } /*! @@ -2966,69 +2983,62 @@ void QGraphicsItem::setVerticalShear(qreal shear) This convenience function sets the horizontal shear to \a sh and the vertical shear to \a sv. + \warning The value doesn't take in account any shearing set with the setTransform() method. + \sa setHorizontalShear(), setVerticalShear() */ void QGraphicsItem::setShear(qreal sh, qreal sv) { - setHorizontalShear(sh); - setVerticalShear(sv); + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->horizontalShear = sh; + d_ptr->transformData->verticalShear = sv; + d_ptr->dirtySceneTransform = 1; } /*! \since 4.6 - Returns the transformation origin for the transformation properties. + Returns the origin point using for transformation in item coordinate. The default is QPointF(0,0). - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - \sa setTransformOrigin(), {Transformations} */ QPointF QGraphicsItem::transformOrigin() const { - const QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - return QPointF(decomposed->xOrigin, decomposed->yOrigin); + if (!d_ptr->transformData) + return QPointF(0,0); + return QPointF(d_ptr->transformData->xOrigin, d_ptr->transformData->yOrigin); } /*! - \fn inline void setTransformOrigin(qreal x, qreal y) - \since 4.6 - This is an overloaded member function, provided for convenience. - Sets the transformation origin for the transformation - properties to the point(\a x, \a y). + Sets the origin for transformation in item coordinate - \sa setTransformOrigin(), {Transformations} + \sa transformOrigin(), {Transformations} */ +void QGraphicsItem::setTransformOrigin(const QPointF &origin) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xOrigin = origin.x(); + d_ptr->transformData->yOrigin = origin.y(); + d_ptr->dirtySceneTransform = 1; +} /*! - \since 4.6 - - Sets the transformation origin for the transformation properties to \a origin. - This does not apply to the transformation set by setTransform. + \fn inline void setTransformOrigin(qreal x, qreal y) - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. + \since 4.6 + \overload - \sa transformOrigin(), {Transformations} + \sa setTransformOrigin(), {Transformations} */ -void QGraphicsItem::setTransformOrigin(const QPointF &origin) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xOrigin = origin.x(); - decomposed->yOrigin = origin.y(); - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} + /*! \obsolete @@ -3056,51 +3066,23 @@ QMatrix QGraphicsItem::sceneMatrix() const \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 4 Unlike transform(), which returns only an item's local transformation, this - function includes the item's (and any parents') position. + function includes the item's (and any parents') position, and all the transfomation properties. - \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System} + \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, {Transformations} */ QTransform QGraphicsItem::sceneTransform() const { - // Check if there's any entry in the transform cache. - QGraphicsScenePrivate *sd = d_ptr->scene ? d_ptr->scene->d_func() : 0; - int index = d_ptr->sceneTransformIndex; - if (sd && index != -1 && sd->validTransforms.testBit(index)) - return sd->sceneTransformCache[index]; - - // Calculate local transform. - QTransform m; - if (d_ptr->hasTransform) { - m = transform(); - if (!d_ptr->pos.isNull()) - m *= QTransform::fromTranslate(d_ptr->pos.x(), d_ptr->pos.y()); - } else if (!d_ptr->pos.isNull()) { - m = QTransform::fromTranslate(d_ptr->pos.x(), d_ptr->pos.y()); - } - - // Combine with parent and add to cache. - if (d_ptr->parent) { - m *= d_ptr->parent->sceneTransform(); - // Don't cache toplevels - if (sd) { - if (index == -1) { - if (!sd->freeSceneTransformSlots.isEmpty()) { - index = sd->freeSceneTransformSlots.last(); - sd->freeSceneTransformSlots.pop_back(); - } else { - index = sd->sceneTransformCache.size(); - } - d_ptr->sceneTransformIndex = index; - if (index >= sd->validTransforms.size()) { - sd->validTransforms.resize(index + 1); - sd->sceneTransformCache.resize(index + 1); - } - } - sd->validTransforms.setBit(index, 1); - sd->sceneTransformCache[index] = m; - } + if (d_ptr->dirtySceneTransform) { + // This item and all its descendants have dirty scene transforms. + // We're about to validate this item's scene transform, so we have to + // invalidate all the children; otherwise there's no way for the descendants + // to detect that the ancestor has changed. + d_ptr->invalidateChildrenSceneTransform(); } - return m; + + QGraphicsItem *that = const_cast<QGraphicsItem *>(this); + d_ptr->ensureSceneTransformRecursive(&that); + return d_ptr->sceneTransform; } /*! @@ -3150,17 +3132,17 @@ QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) c // First translate the base untransformable item. QPointF mappedPoint = (untransformedAncestor->sceneTransform() * viewportTransform).map(QPointF(0, 0)); + + // COMBINE QTransform matrix; matrix.translate(mappedPoint.x(), mappedPoint.y()); - matrix = untransformedAncestor->transform() * matrix; + if (untransformedAncestor->d_ptr->transformData) + matrix = untransformedAncestor->d_ptr->transformData->computedFullTransform() * matrix; // Then transform and translate all children. for (int i = 0; i < parents.size(); ++i) { const QGraphicsItem *parent = parents.at(i); - QPointF pos = parent->pos(); - QTransform moveMatrix; - moveMatrix.translate(pos.x(), pos.y()); - matrix = (parent->transform() * moveMatrix) * matrix; + parent->d_ptr->combineTransformFromParent(&matrix); } return matrix; @@ -3203,51 +3185,40 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co if (parent == other) { if (ok) *ok = true; - const QPointF &itemPos = d_ptr->pos; - if (itemPos.isNull()) - return d_ptr->hasTransform ? transform() : QTransform(); - if (d_ptr->hasTransform) - return transform() * QTransform::fromTranslate(itemPos.x(), itemPos.y()); - return QTransform::fromTranslate(itemPos.x(), itemPos.y()); + QTransform x; + d_ptr->combineTransformFromParent(&x); + return x; } // This is other's parent if (otherParent == this) { const QPointF &otherPos = other->d_ptr->pos; - if (other->d_ptr->hasTransform) { - QTransform otherToParent = other->transform(); - if (!otherPos.isNull()) - otherToParent *= QTransform::fromTranslate(otherPos.x(), otherPos.y()); + if (other->d_ptr->transformData) { + QTransform otherToParent; + other->d_ptr->combineTransformFromParent(&otherToParent); return otherToParent.inverted(ok); - } else { - if (ok) - *ok = true; - return QTransform::fromTranslate(-otherPos.x(), -otherPos.y()); } + if (ok) + *ok = true; + return QTransform::fromTranslate(-otherPos.x(), -otherPos.y()); } // Siblings if (parent == otherParent) { - bool hasTr = d_ptr->hasTransform; - bool otherHasTr = other->d_ptr->hasTransform; + // COMBINE const QPointF &itemPos = d_ptr->pos; const QPointF &otherPos = other->d_ptr->pos; - - if (!hasTr && !otherHasTr) { + if (!d_ptr->transformData && !other->d_ptr->transformData) { QPointF delta = itemPos - otherPos; if (ok) *ok = true; return QTransform::fromTranslate(delta.x(), delta.y()); } - QTransform itemToParent = QTransform::fromTranslate(itemPos.x(), itemPos.y()); - if (hasTr) - itemToParent = itemPos.isNull() ? transform() : transform() * itemToParent; - - QTransform otherToParent = QTransform::fromTranslate(otherPos.x(), otherPos.y()); - if (otherHasTr) - otherToParent = otherPos.isNull() ? other->transform() : other->transform() * otherToParent; - + QTransform itemToParent; + d_ptr->combineTransformFromParent(&itemToParent); + QTransform otherToParent; + other->d_ptr->combineTransformFromParent(&otherToParent); return itemToParent * otherToParent.inverted(ok); } @@ -3283,11 +3254,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co QTransform x; const QGraphicsItem *p = child; do { - const QGraphicsItemPrivate *pd = p->d_ptr; - if (pd->hasTransform) - x *= p->transform(); - if (!pd->pos.isNull()) - x *= QTransform::fromTranslate(pd->pos.x(), pd->pos.y()); + p->d_ptr->combineTransformToParent(&x); } while ((p = p->d_ptr->parent) && p != root); if (parentOfOther) return x.inverted(ok); @@ -3309,35 +3276,30 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { - QTransform oldTransform = this->transform(); - QTransform newTransform; - if (!combine) - newTransform = QTransform(matrix); - else - newTransform = QTransform(matrix) * oldTransform; - if (oldTransform == newTransform) - return; + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - // Notify the item that the matrix is changing. - QVariant newTransformVariant(itemChange(ItemMatrixChange, - qVariantFromValue<QMatrix>(newTransform.toAffine()))); - newTransform = QTransform(qVariantValue<QMatrix>(newTransformVariant)); - if (oldTransform == newTransform) + QTransform newTransform(combine ? QTransform(matrix) * d_ptr->transformData->transform : QTransform(matrix)); + if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. - d_ptr->fullUpdateHelper(true, true); - prepareGeometryChange(); - d_ptr->hasTransform = !newTransform.isIdentity(); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); - d_ptr->dirtyTransformComponents = 1; - d_ptr->dirtyTransform = 0; - d_ptr->invalidateSceneTransformCache(); + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setTransformHelper(newTransform); + return; + } + + // Notify the item that the transformation matrix is changing. + const QVariant newMatrixVariant = qVariantFromValue<QMatrix>(newTransform.toAffine()); + newTransform = QTransform(qVariantValue<QMatrix>(itemChange(ItemMatrixChange, newMatrixVariant))); + if (d_ptr->transformData->transform == newTransform) + return; + // Update and set the new transformation. + d_ptr->setTransformHelper(newTransform); + // Send post-notification. - // NB! We have to change the value from QMatrix to QTransform. - qVariantSetValue<QTransform>(newTransformVariant, newTransform); - itemChange(ItemTransformHasChanged, newTransformVariant); + itemChange(ItemTransformHasChanged, qVariantFromValue<QTransform>(newTransform)); } /*! @@ -3355,37 +3317,34 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) to map an item coordiate to a scene coordinate, or mapFromScene() to map from scene coordinates to item coordinates. - \warning using this function conflicts with using the transformation properties. - If you set a transformation, getting the properties will return default values. + \warning using this function doesnt affect the value of the transformation properties - \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin() {The Graphics View Coordinate System} + \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin(), {The Graphics View Coordinate System}, {Transformations} */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { - QTransform oldTransform = this->transform(); - QTransform newTransform; - if (!combine) - newTransform = matrix; - else - newTransform = matrix * oldTransform; - if (oldTransform == newTransform) + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + + QTransform newTransform(combine ? matrix * d_ptr->transformData->transform : matrix); + if (d_ptr->transformData->transform == newTransform) return; + // Update and set the new transformation. + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setTransformHelper(newTransform); + return; + } + // Notify the item that the transformation matrix is changing. const QVariant newTransformVariant(itemChange(ItemTransformChange, qVariantFromValue<QTransform>(newTransform))); newTransform = qVariantValue<QTransform>(newTransformVariant); - if (oldTransform == newTransform) + if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. - d_ptr->fullUpdateHelper(true, true); - prepareGeometryChange(); - d_ptr->hasTransform = !newTransform.isIdentity(); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); - d_ptr->dirtyTransformComponents = 1; - d_ptr->dirtyTransform = 0; - d_ptr->invalidateSceneTransformCache(); + d_ptr->setTransformHelper(newTransform); // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -3427,8 +3386,7 @@ void QGraphicsItem::resetTransform() \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6 - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this functionhas no effect on the zRotation value \sa setTransform(), transform(), scale(), shear(), translate() */ @@ -3449,8 +3407,7 @@ void QGraphicsItem::rotate(qreal angle) \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7 - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this function has no effect on the xScale or yScale value \sa setTransform(), transform() */ @@ -3465,8 +3422,7 @@ void QGraphicsItem::scale(qreal sx, qreal sy) Shears the current item transformation by (\a sh, \a sv). - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this function has no effect on the horizontalShear or verticalShear value \sa setTransform(), transform() */ @@ -3485,9 +3441,6 @@ void QGraphicsItem::shear(qreal sh, qreal sv) setPos() instead; this function changes the item's translation, which is conceptually separate from its position. - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. - \sa setTransform(), transform() */ void QGraphicsItem::translate(qreal dx, qreal dy) @@ -3566,9 +3519,13 @@ void QGraphicsItem::setZValue(qreal z) if (newZ == d_ptr->z) return; d_ptr->z = newZ; - d_ptr->fullUpdateHelper(); + if (d_ptr->parent) + d_ptr->parent->d_ptr->needSortChildren = 1; + else if (d_ptr->scene) + d_ptr->scene->d_func()->needSortTopLevelItems = 1; if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); // Invalidate any sort caching; arrival of a new item means we need to // resort. d_ptr->scene->d_func()->invalidateSortCache(); @@ -3596,6 +3553,9 @@ void QGraphicsItem::setZValue(qreal z) */ QRectF QGraphicsItem::childrenBoundingRect() const { + if (!d_ptr->dirtyChildrenBoundingRect) + return d_ptr->childrenBoundingRect; + QRectF childRect; QTransform x; d_ptr->childrenBoundingRectHelper(&x, &childRect); @@ -3644,12 +3604,13 @@ QRectF QGraphicsItem::childrenBoundingRect() const QRectF QGraphicsItem::sceneBoundingRect() const { // Find translate-only offset + // COMBINE QPointF offset; const QGraphicsItem *parentItem = this; const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr; - if (itemd->hasTransform) + if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); @@ -4226,7 +4187,7 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore // No scene, or if the scene is updating everything, means we have nothing // to do. The only exception is if the scene tracks the growing scene rect. return (!visible && !ignoreVisibleBit) - || (dirty && !ignoreDirtyBit) + || (!ignoreDirtyBit && fullUpdatePending) || !scene || (scene->d_func()->updateAll && scene->d_func()->hasSceneRect) || (!ignoreClipping && (childrenClippedToShape() && isClippedAway())) @@ -4236,141 +4197,6 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore /*! \internal - Asks the scene to mark this item's scene rect as dirty, requesting a - redraw. This does not invalidate any cache. - - The \a force argument is for the update call in setVisible(), which is the - only case where the item's background should be marked as dirty even when - the item isn't visible. -*/ -void QGraphicsItemPrivate::updateHelper(const QRectF &rect, bool force, bool maybeDirtyClipPath) -{ - // No scene, or if the scene is updating everything, means we have nothing - // to do. The only exception is if the scene tracks the growing scene rect. - if (discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/force)) - return; - - if (rect.isNull()) - dirty = 1; - scene->itemUpdated(q_ptr, rect); -} - -/*! - \internal - - Propagates updates to \a item and all its children. -*/ -void QGraphicsItemPrivate::fullUpdateHelper(bool childrenOnly, bool maybeDirtyClipPath, bool ignoreOpacity) -{ - if (discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/false, - /*ignoreDirtyBit=*/true, ignoreOpacity)) { - return; - } - - if (!childrenOnly && !dirty) { - // Effectively the same as updateHelper(QRectF(), false, maybeDirtyClipPath). - dirty = 1; - scene->itemUpdated(q_ptr, QRectF()); - } - - if (dirtyChildren || childrenClippedToShape()) { - // Unnecessary to update children as well. - return; - } - - if (ancestorFlags & AncestorClipsChildren) { - Q_Q(QGraphicsItem); - // Check if we can avoid updating all children. - QGraphicsItem *p = parent; - QRectF br = q->boundingRect(); - while (p) { - if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) { - bool ok; - QTransform x = q->itemTransform(p, &ok); - if (!ok) - break; - if (x.mapRect(br).contains(p->boundingRect())) - return; - } - p = p->d_ptr->parent; - if (!p || !(p->d_ptr->ancestorFlags & AncestorClipsChildren)) - break; - // ### check one level only - break; - } - } - foreach (QGraphicsItem *child, children) - child->d_ptr->fullUpdateHelper(false, maybeDirtyClipPath); - dirtyChildren = 1; -} - -static inline bool allChildrenCombineOpacityHelper(QGraphicsItem *parent) -{ - Q_ASSERT(parent); - if (parent->flags() & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) - return false; - - const QList<QGraphicsItem *> children(parent->childItems()); - for (int i = 0; i < children.size(); ++i) { - if (children.at(i)->flags() & QGraphicsItem::ItemIgnoresParentOpacity) - return false; - } - return true; -} - -void QGraphicsItemPrivate::updateEffectiveOpacity() -{ - Q_Q(QGraphicsItem); - if (parent) { - resolveEffectiveOpacity(parent->effectiveOpacity()); - parent->d_ptr->allChildrenCombineOpacity = allChildrenCombineOpacityHelper(parent); - } else { - resolveEffectiveOpacity(1.0); - } - allChildrenCombineOpacity = allChildrenCombineOpacityHelper(q); -} - -/*! - \internal - - Resolves and propagates this item's effective opacity to its children. -*/ -void QGraphicsItemPrivate::resolveEffectiveOpacity(qreal parentEffectiveOpacity) -{ - Q_Q(QGraphicsItem); - QGraphicsItem::GraphicsItemFlags myFlags = q->flags(); - QGraphicsItem::GraphicsItemFlags parentFlags = parent ? parent->flags() : QGraphicsItem::GraphicsItemFlags(0); - - // My local opacity is always part of my effective opacity. - qreal myEffectiveOpacity = q->opacity(); - - // If I have a parent, and I don't ignore my parent's opacity, and my - // parent propagates to me, then combine my local opacity with my parent's - // effective opacity into my effective opacity. - if (parent - && !(myFlags & QGraphicsItem::ItemIgnoresParentOpacity) - && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { - myEffectiveOpacity *= parentEffectiveOpacity; - } - - // Set this item's resolved opacity. - if (qFuzzyIsNull(myEffectiveOpacity - 1)) { - // Opaque, unset effective opacity. - hasEffectiveOpacity = 0; - unsetExtra(ExtraEffectiveOpacity); - } else { - hasEffectiveOpacity = 1; - setExtra(ExtraEffectiveOpacity, myEffectiveOpacity); - } - - // Resolve children always. - for (int i = 0; i < children.size(); ++i) - children.at(i)->d_ptr->resolveEffectiveOpacity(myEffectiveOpacity); -} - -/*! - \internal - Resolves the stacking depth of this object and all its children. */ void QGraphicsItemPrivate::resolveDepth(int parentDepth) @@ -4383,22 +4209,9 @@ void QGraphicsItemPrivate::resolveDepth(int parentDepth) /*! \internal */ -void QGraphicsItemPrivate::invalidateSceneTransformCache() -{ - if (!scene || (parent && sceneTransformIndex == -1)) - return; - if (sceneTransformIndex != -1) - scene->d_func()->validTransforms.setBit(sceneTransformIndex, 0); - for (int i = 0; i < children.size(); ++i) - children.at(i)->d_ptr->invalidateSceneTransformCache(); -} - -/*! - \internal -*/ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) { - child->d_ptr->siblingIndex = children.size(); + needSortChildren = 1; children.append(child); } @@ -4407,14 +4220,7 @@ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) */ void QGraphicsItemPrivate::removeChild(QGraphicsItem *child) { - int idx = child->d_ptr->siblingIndex; - int size = children.size(); - for (int i = idx; i < size - 1; ++i) { - QGraphicsItem *p = children[i + 1]; - children[i] = p; - p->d_ptr->siblingIndex = i; - } - children.removeLast(); + children.removeOne(child); } /*! @@ -4503,17 +4309,11 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n // Find closest clip ancestor and transform. Q_Q(QGraphicsItem); - QTransform thisToParentTransform = hasTransform - ? q->transform() * QTransform::fromTranslate(newPos.x(), newPos.y()) - : QTransform::fromTranslate(newPos.x(), newPos.y()); + // COMBINE + QTransform thisToParentTransform = transformToParent(); QGraphicsItem *clipParent = parent; while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) { - if (clipParent->d_ptr->hasTransform) - thisToParentTransform *= clipParent->transform(); - if (!clipParent->d_ptr->pos.isNull()) { - thisToParentTransform *= QTransform::fromTranslate(clipParent->d_ptr->pos.x(), - clipParent->d_ptr->pos.y()); - } + thisToParentTransform *= clipParent->d_ptr->transformToParent(); clipParent = clipParent->d_ptr->parent; } @@ -4555,6 +4355,35 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n } } +// Traverses all the ancestors up to the top-level and updates the pointer to +// always point to the top-most item that has a dirty scene transform. +// It then backtracks to the top-most dirty item and start calculating the +// scene transform by combining the item's transform (+pos) with the parent's +// cached scene transform (which we at this point know for sure is valid). +void QGraphicsItemPrivate::ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem) +{ + Q_ASSERT(topMostDirtyItem); + + if (dirtySceneTransform) + *topMostDirtyItem = q_ptr; + + if (parent) + parent->d_ptr->ensureSceneTransformRecursive(topMostDirtyItem); + + if (*topMostDirtyItem == q_ptr) { + if (!dirtySceneTransform) + return; // OK, neither my ancestors nor I have dirty scene transforms. + *topMostDirtyItem = 0; + } else if (*topMostDirtyItem) { + return; // Continue backtrack. + } + + // COMBINE my transform with the parent's scene transform. + sceneTransform = parent ? parent->d_ptr->sceneTransform : QTransform(); + combineTransformFromParent(&sceneTransform); + dirtySceneTransform = 0; +} + /*! \internal @@ -4606,16 +4435,12 @@ void QGraphicsItem::update(const QRectF &rect) } } // Only invalidate cache; item is already dirty. - if (d_ptr->dirty) + if (d_ptr->fullUpdatePending) return; - } else if (d_ptr->discardUpdateRequest()) { - return; } - // Effectively the same as updateHelper(rect); - if (rect.isNull()) - d_ptr->dirty = 1; - d_ptr->scene->itemUpdated(this, rect); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this, rect); } /*! @@ -4713,7 +4538,7 @@ void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect) exposed -= r.translated(dx, dy); foreach (QRect rect, exposed.rects()) update(rect); - d_ptr->updateHelper(); + d->scene->d_func()->markDirty(this); } else { update(rect); } @@ -4742,13 +4567,7 @@ void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect) static const QLineF left(0, 0, -1, 0); static const QLineF right(0, 0, 1, 0); - QTransform deviceTr; - if (d->itemIsUntransformable()) { - deviceTr = deviceTransform(view->viewportTransform()); - } else { - deviceTr = sceneTransform() * view->viewportTransform(); - } - + QTransform deviceTr = deviceTransform(view->viewportTransform()); QRect deviceScrollRect = deviceTr.mapRect(scrollRect).toRect(); QLineF v1 = deviceTr.map(right); QLineF v2 = deviceTr.map(down); @@ -4880,9 +4699,10 @@ QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point */ QPointF QGraphicsItem::mapToParent(const QPointF &point) const { - if (!d_ptr->hasTransform) + // COMBINE + if (!d_ptr->transformData) return point + d_ptr->pos; - return transform().map(point) + d_ptr->pos; + return d_ptr->transformToParent().map(point); } /*! @@ -4947,9 +4767,10 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect */ QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const { - if (!d_ptr->hasTransform) + // COMBINE + if (!d_ptr->transformData) return rect.translated(d_ptr->pos); - return transform().map(rect).translated(d_ptr->pos); + return d_ptr->transformToParent().map(rect); } /*! @@ -5016,8 +4837,10 @@ QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rec */ QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const { - QRectF r = !d_ptr->hasTransform ? rect : transform().mapRect(rect); - return r.translated(d_ptr->pos); + // COMBINE + if (!d_ptr->transformData) + return rect.translated(d_ptr->pos); + return d_ptr->transformToParent().mapRect(rect); } /*! @@ -5088,8 +4911,10 @@ QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &r */ QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const { - QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().mapRect(r) : r; + // COMBINE + if (!d_ptr->transformData) + return rect.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().mapRect(rect); } /*! @@ -5148,9 +4973,10 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &p */ QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const { - if (!d_ptr->hasTransform) + // COMBINE + if (!d_ptr->transformData) return polygon.translated(d_ptr->pos); - return transform().map(polygon).translated(d_ptr->pos); + return d_ptr->transformToParent().map(polygon); } /*! @@ -5192,9 +5018,10 @@ QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterP */ QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const { - if (!d_ptr->hasTransform) + // COMBINE + if (!d_ptr->transformData) return path.translated(d_ptr->pos); - return transform().map(path).translated(d_ptr->pos); + return d_ptr->transformToParent().map(path); } /*! @@ -5243,8 +5070,9 @@ QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &poi */ QPointF QGraphicsItem::mapFromParent(const QPointF &point) const { - if (d_ptr->hasTransform) - return transform().inverted().map(point - d_ptr->pos); + // COMBINE + if (d_ptr->transformData) + return d_ptr->transformToParent().inverted().map(point); return point - d_ptr->pos; } @@ -5311,8 +5139,10 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &re */ QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const { - QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(r) : r; + // COMBINE + if (!d_ptr->transformData) + return rect.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(rect); } /*! @@ -5367,9 +5197,10 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPolygonF */ QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const { - QPolygonF p = polygon; - p.translate(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(p) : p; + // COMBINE + if (!d_ptr->transformData) + return polygon.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(polygon); } /*! @@ -5409,9 +5240,10 @@ QPainterPath QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPainte */ QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const { - QPainterPath p(path); - p.translate(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(p) : p; + // COMBINE + if (!d_ptr->transformData) + return path.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(path); } /*! @@ -5929,7 +5761,8 @@ void QGraphicsItem::focusOutEvent(QFocusEvent *event) void QGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); - d_ptr->updateHelper(); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this); } /*! @@ -5957,7 +5790,8 @@ void QGraphicsItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) void QGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); - d_ptr->updateHelper(); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this); } /*! @@ -6500,7 +6334,6 @@ void QGraphicsItem::addToIndex() } if (d_ptr->scene) d_ptr->scene->d_func()->addToIndex(this); - d_ptr->updateHelper(); } /*! @@ -6516,7 +6349,6 @@ void QGraphicsItem::removeFromIndex() // ### remove from child index only if applicable return; } - d_ptr->updateHelper(); if (d_ptr->scene) d_ptr->scene->d_func()->removeFromIndex(this); } @@ -6537,11 +6369,30 @@ void QGraphicsItem::removeFromIndex() void QGraphicsItem::prepareGeometryChange() { if (d_ptr->scene) { - d_ptr->updateHelper(QRectF(), false, /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); + d_ptr->geometryChanged = 1; + d_ptr->paintedViewBoundingRectsNeedRepaint = 1; + QGraphicsScenePrivate *scenePrivate = d_ptr->scene->d_func(); + scenePrivate->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); + + // For compatibility reasons, we have to update the item's old geometry + // if someone is connected to the changed signal or the scene has no views. + // Note that this has to be done *after* markDirty to ensure that + // _q_processDirtyItems is called before _q_emitUpdated. + if ((scenePrivate->connectedSignals & scenePrivate->changedSignalMask) + || scenePrivate->views.isEmpty()) { + d_ptr->scene->update(sceneTransform().mapRect(boundingRect())); + } + scenePrivate->removeFromIndex(this); } + QGraphicsItem *parent = this; + while ((parent = parent->d_ptr->parent)) + parent->d_ptr->dirtyChildrenBoundingRect = 1; + if (d_ptr->inSetPosHelper) return; @@ -8202,7 +8053,6 @@ void QGraphicsPixmapItem::setTransformationMode(Qt::TransformationMode mode) { Q_D(QGraphicsPixmapItem); if (mode != d->transformationMode) { - d_ptr->updateHelper(); d->transformationMode = mode; update(); } @@ -9584,6 +9434,8 @@ void QGraphicsItemGroup::addToGroup(QGraphicsItem *item) return; } + // COMBINE + // ### Use itemTransform() instead. QTransform oldSceneMatrix = item->sceneTransform(); item->setPos(mapFromItem(item, 0, 0)); item->setParentItem(this); @@ -9825,6 +9677,12 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) case QGraphicsItem::ItemUsesExtendedStyleOption: str = "ItemUsesExtendedStyleOption"; break; + case QGraphicsItem::ItemHasNoContents: + str = "ItemHasNoContents"; + break; + case QGraphicsItem::ItemSendsGeometryChanges: + str = "ItemSendsGeometryChanges"; + break; } debug << str; return debug; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 11e05d0..7c46b87 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -95,7 +95,9 @@ public: ItemIgnoresParentOpacity = 0x40, ItemDoesntPropagateOpacityToChildren = 0x80, ItemStacksBehindParent = 0x100, - ItemUsesExtendedStyleOption = 0x200 + ItemUsesExtendedStyleOption = 0x200, + ItemHasNoContents = 0x400, + ItemSendsGeometryChanges = 0x800 // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag. }; Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index bedcf20..7501aa8 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -102,25 +102,12 @@ class Q_AUTOTEST_EXPORT QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsItem) public: - struct TransformData - { - TransformData() : rotationX(0),rotationY(0),rotationZ(0),scaleX(1),scaleY(1), dirty(true) {} - QTransform baseTransform; - QTransform transform; - QPointF transformCenter; - qreal rotationX,rotationY,rotationZ,scaleX,scaleY; - bool dirty; - }; enum Extra { - ExtraTransform, ExtraToolTip, ExtraCursor, ExtraCacheData, ExtraMaxDeviceCoordCacheSize, ExtraBoundingRegionGranularity, - ExtraOpacity, - ExtraEffectiveOpacity, - ExtraDecomposedTransform, ExtraGestures }; @@ -133,9 +120,10 @@ public: inline QGraphicsItemPrivate() : z(0), + opacity(1.), scene(0), parent(0), - siblingIndex(-1), + transformData(0), index(-1), depth(0), acceptedMouseButtons(0x1f), @@ -149,13 +137,10 @@ public: isMemberOfGroup(0), handlesChildEvents(0), itemDiscovered(0), - hasTransform(0), hasCursor(0), ancestorFlags(0), cacheMode(0), hasBoundingRegionGranularity(0), - hasOpacity(0), - hasEffectiveOpacity(0), isWidget(0), dirty(0), dirtyChildren(0), @@ -163,15 +148,18 @@ public: dirtyClipPath(1), emptyClipPath(0), inSetPosHelper(0), + needSortChildren(1), + allChildrenDirty(0), + fullUpdatePending(0), flags(0), - allChildrenCombineOpacity(1), - hasDecomposedTransform(0), - dirtyTransform(0), - dirtyTransformComponents(0), + dirtyChildrenBoundingRect(1), + paintedViewBoundingRectsNeedRepaint(0), + dirtySceneTransform(1), + geometryChanged(0), + inDestructor(0), acceptTouchEvents(0), acceptedTouchBeginEvent(0), globalStackingOrder(-1), - sceneTransformIndex(-1), q_ptr(0) { } @@ -184,26 +172,29 @@ public: void setIsMemberOfGroup(bool enabled); void remapItemPos(QEvent *event, QGraphicsItem *item); QPointF genericMapFromScene(const QPointF &pos, const QWidget *viewport) const; - bool itemIsUntransformable() const; + inline bool itemIsUntransformable() const + { + return (flags & QGraphicsItem::ItemIgnoresTransformations) + || (ancestorFlags & AncestorIgnoresTransformations); + } + void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const; + void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const; + // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4. virtual QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const; static bool movableAncestorIsSelected(const QGraphicsItem *item); void setPosHelper(const QPointF &pos); + void setTransformHelper(const QTransform &transform); void setVisibleHelper(bool newVisible, bool explicitly, bool update = true); void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true); bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, bool ignoreDirtyBit = false, bool ignoreOpacity = false) const; - void updateHelper(const QRectF &rect = QRectF(), bool force = false, bool maybeDirtyClipPath = false); - void fullUpdateHelper(bool childrenOnly = false, bool maybeDirtyClipPath = false, bool ignoreOpacity = false); - void updateEffectiveOpacity(); - void resolveEffectiveOpacity(qreal effectiveParentOpacity); void resolveDepth(int parentDepth); - void invalidateSceneTransformCache(); void addChild(QGraphicsItem *child); void removeChild(QGraphicsItem *child); - void setParentItemHelper(QGraphicsItem *parent, bool deleting); + void setParentItemHelper(QGraphicsItem *parent); void childrenBoundingRectHelper(QTransform *x, QRectF *rect); void initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform, const QRegion &exposedRegion, bool allItems = false) const; @@ -297,12 +288,67 @@ public: void invalidateCachedClipPathRecursively(bool childrenOnly = false, const QRectF &emptyIfOutsideThisRect = QRectF()); void updateCachedClipPathFromSetPosHelper(const QPointF &newPos); + void ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem); + + inline void invalidateChildrenSceneTransform() + { + for (int i = 0; i < children.size(); ++i) + children.at(i)->d_ptr->dirtySceneTransform = 1; + } + + inline qreal calcEffectiveOpacity() const + { + qreal o = opacity; + QGraphicsItem *p = parent; + int myFlags = flags; + while (p) { + int parentFlags = p->d_ptr->flags; + + // If I have a parent, and I don't ignore my parent's opacity, and my + // parent propagates to me, then combine my local opacity with my parent's + // effective opacity into my effective opacity. + if ((myFlags & QGraphicsItem::ItemIgnoresParentOpacity) + || (parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { + break; + } + + o *= p->d_ptr->opacity; + p = p->d_ptr->parent; + myFlags = parentFlags; + } + return o; + } inline bool isFullyTransparent() const - { return hasEffectiveOpacity && qFuzzyIsNull(q_func()->effectiveOpacity()); } + { + if (opacity < 0.001) + return true; + if (!parent) + return false; + + return calcEffectiveOpacity() < 0.001; + } + + inline qreal effectiveOpacity() const { + if (!parent || !opacity) + return opacity; + + return calcEffectiveOpacity(); + } inline bool childrenCombineOpacity() const - { return allChildrenCombineOpacity || children.isEmpty(); } + { + if (!children.size()) + return true; + if (flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) + return false; + + for (int i = 0; i < children.size(); ++i) { + if (children.at(i)->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity) + return false; + } + return true; + } inline bool isClippedAway() const { return !dirtyClipPath && q_func()->isClipped() && (emptyClipPath || cachedClipPath.isEmpty()); } @@ -317,13 +363,21 @@ public: || (childrenCombineOpacity() && isFullyTransparent()); } + inline QTransform transformToParent() const; + QPainterPath cachedClipPath; + QRectF childrenBoundingRect; + QRectF needsRepaint; + QMap<QWidget *, QRect> paintedViewBoundingRects; QPointF pos; qreal z; + qreal opacity; QGraphicsScene *scene; QGraphicsItem *parent; QList<QGraphicsItem *> children; - int siblingIndex; + class TransformData; + TransformData *transformData; + QTransform sceneTransform; int index; int depth; @@ -363,13 +417,10 @@ public: quint32 isMemberOfGroup : 1; quint32 handlesChildEvents : 1; quint32 itemDiscovered : 1; - quint32 hasTransform : 1; quint32 hasCursor : 1; quint32 ancestorFlags : 3; quint32 cacheMode : 2; quint32 hasBoundingRegionGranularity : 1; - quint32 hasOpacity : 1; - quint32 hasEffectiveOpacity : 1; quint32 isWidget : 1; quint32 dirty : 1; quint32 dirtyChildren : 1; @@ -377,91 +428,69 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; + quint32 needSortChildren : 1; + quint32 allChildrenDirty : 1; + quint32 fullUpdatePending : 1; // New 32 bits - quint32 flags : 10; - quint32 allChildrenCombineOpacity : 1; - quint32 hasDecomposedTransform : 1; - quint32 dirtyTransform : 1; - quint32 dirtyTransformComponents : 1; + quint32 flags : 12; + quint32 dirtyChildrenBoundingRect : 1; + quint32 paintedViewBoundingRectsNeedRepaint : 1; + quint32 dirtySceneTransform : 1; + quint32 geometryChanged : 1; + quint32 inDestructor : 1; quint32 acceptTouchEvents : 1; quint32 acceptedTouchBeginEvent : 1; - quint32 padding : 16; // feel free to use + quint32 unused : 13; // feel free to use // Optional stacking order int globalStackingOrder; - int sceneTransformIndex; + QGraphicsItem *q_ptr; +}; - struct DecomposedTransform; - DecomposedTransform *decomposedTransform() const +struct QGraphicsItemPrivate::TransformData { + QTransform transform; + qreal xScale; + qreal yScale; + qreal xRotation; + qreal yRotation; + qreal zRotation; + qreal horizontalShear; + qreal verticalShear; + qreal xOrigin; + qreal yOrigin; + + TransformData() : + xScale(1.0), yScale(1.0), xRotation(0.0), yRotation(0.0), zRotation(0.0), + horizontalShear(0.0), verticalShear(0.0), xOrigin(0.0), yOrigin(0.0) + {} + + QTransform computedFullTransform() const { - QGraphicsItemPrivate *that = const_cast<QGraphicsItemPrivate *>(this); - DecomposedTransform *decomposed; - if (hasDecomposedTransform) { - decomposed = qVariantValue<DecomposedTransform *>(extra(ExtraDecomposedTransform)); - } else { - decomposed = new DecomposedTransform; - that->setExtra(ExtraDecomposedTransform, qVariantFromValue<DecomposedTransform *>(decomposed)); - that->hasDecomposedTransform = 1; - if (!dirtyTransformComponents) - decomposed->reset(); - } - if (dirtyTransformComponents) { - decomposed->initFrom(q_ptr->transform()); - that->dirtyTransformComponents = 0; - } - return decomposed; + QTransform x; + x.translate(xOrigin, yOrigin); + x = transform * x; + x.rotate(xRotation, Qt::XAxis); + x.rotate(yRotation, Qt::YAxis); + x.rotate(zRotation, Qt::ZAxis); + x.shear(horizontalShear, verticalShear); + x.scale(xScale, yScale); + x.translate(-xOrigin, -yOrigin); + return x; } - - struct DecomposedTransform { - qreal xScale; - qreal yScale; - qreal xRotation; - qreal yRotation; - qreal zRotation; - qreal horizontalShear; - qreal verticalShear; - qreal xOrigin; - qreal yOrigin; - - inline void reset() - { - xScale = 1.0; - yScale = 1.0; - xRotation = 0.0; - yRotation = 0.0; - zRotation = 0.0; - horizontalShear = 0.0; - verticalShear = 0.0; - xOrigin = 0.0; - yOrigin = 0.0; - } - - inline void initFrom(const QTransform &x) - { - reset(); - // ### decompose transform - Q_UNUSED(x); - } - - inline void generateTransform(QTransform *x) const - { - x->translate(xOrigin, yOrigin); - x->rotate(xRotation, Qt::XAxis); - x->rotate(yRotation, Qt::YAxis); - x->rotate(zRotation, Qt::ZAxis); - x->shear(horizontalShear, verticalShear); - x->scale(xScale, yScale); - x->translate(-xOrigin, -yOrigin); - } - }; - - QGraphicsItem *q_ptr; }; -QT_END_NAMESPACE +/* + return the full transform of the item to the parent. This include the position and all the transform data +*/ +inline QTransform QGraphicsItemPrivate::transformToParent() const +{ + QTransform matrix; + combineTransformToParent(&matrix); + return matrix; +} -Q_DECLARE_METATYPE(QGraphicsItemPrivate::DecomposedTransform *) +QT_END_NAMESPACE #endif // QT_NO_GRAPHICSVIEW diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index cffaa40..291b3af 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -39,7 +39,6 @@ ** ****************************************************************************/ -static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; /*! \class QGraphicsScene @@ -252,6 +251,8 @@ static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; QT_BEGIN_NAMESPACE +static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2); + static inline bool QRectF_intersects(const QRectF &s, const QRectF &r) { qreal xp = s.left(); @@ -335,8 +336,9 @@ QGraphicsScenePrivate::QGraphicsScenePrivate() hasSceneRect(false), updateAll(false), calledEmitUpdated(false), + processDirtyItemsEmitted(false), selectionChanging(0), - dirtyItemResetPending(false), + needSortTopLevelItems(true), regenerateIndex(true), purgePending(false), indexTimerId(0), @@ -414,7 +416,7 @@ QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF & if (QGraphicsItem *item = unindexedItems.at(i)) { if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) continue; - if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0)) + if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent()) itemsInRect << item; } } @@ -422,7 +424,7 @@ QList<QGraphicsItem *> QGraphicsScenePrivate::estimateItemsInRect(const QRectF & if (QGraphicsItem *item = indexedItems.at(i)) { if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) continue; - if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0)) + if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent()) itemsInRect << item; } } @@ -600,7 +602,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() // the optimization that items send updates directly to the views, but it // needs to happen in order to keep compatibility with the behavior from // Qt 4.4 and backward. - if (!views.isEmpty() && (connectedSignals & changedSignalMask)) { + if (connectedSignals & changedSignalMask) { for (int i = 0; i < views.size(); ++i) { QGraphicsView *view = views.at(i); if (!view->d_func()->connectedToScene) { @@ -609,13 +611,13 @@ void QGraphicsScenePrivate::_q_emitUpdated() views.at(i), SLOT(updateScene(QList<QRectF>))); } } + } else { + updateAll = false; + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->processPendingUpdates(); + return; } - // Ensure all dirty items's current positions are recorded in the list of - // updated rects. - for (int i = 0; i < dirtyItems.size(); ++i) - updatedRects += dirtyItems.at(i)->sceneBoundingRect(); - // Notify the changes to anybody interested. QList<QRectF> oldUpdatedRects; oldUpdatedRects = updateAll ? (QList<QRectF>() << q->sceneRect()) : updatedRects; @@ -629,7 +631,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() */ void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item) { - item->d_ptr->siblingIndex = topLevelItems.size(); + needSortTopLevelItems = true; topLevelItems.append(item); } @@ -638,14 +640,7 @@ void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item) */ void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item) { - int idx = item->d_ptr->siblingIndex; - int size = topLevelItems.size(); - for (int i = idx; i < size - 1; ++i) { - QGraphicsItem *p = topLevelItems[i + 1]; - topLevelItems[i] = p; - p->d_ptr->siblingIndex = i; - } - topLevelItems.removeLast(); + topLevelItems.removeOne(item); } /*! @@ -680,70 +675,102 @@ void QGraphicsScenePrivate::_q_polishItems() unpolishedItems.clear(); } -/*! - \internal -*/ -void QGraphicsScenePrivate::_q_resetDirtyItems() +void QGraphicsScenePrivate::_q_processDirtyItems() { - for (int i = 0; i < dirtyItems.size(); ++i) { - QGraphicsItem *item = dirtyItems.at(i); - item->d_ptr->dirty = 0; - item->d_ptr->dirtyChildren = 0; - } - dirtyItems.clear(); - dirtyItemResetPending = false; -} + processDirtyItemsEmitted = false; -/*! - \internal -*/ -void QGraphicsScenePrivate::resetDirtyItemsLater() -{ - Q_Q(QGraphicsScene); - if (dirtyItemResetPending) + const bool wasPendingSceneUpdate = calledEmitUpdated; + const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect; + processDirtyItemsRecursive(0); + if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect) + emit q_func()->sceneRectChanged(growingItemsBoundingRect); + + if (wasPendingSceneUpdate) return; - // dirtyItems.reserve(indexedItems.size() + unindexedItems.size()); - dirtyItemResetPending = true; - QMetaObject::invokeMethod(q, "_q_resetDirtyItems", Qt::QueuedConnection); + + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->processPendingUpdates(); + + if (calledEmitUpdated) { + // We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive + // and we cannot wait for the control to reach the eventloop before the + // changed signal is emitted, so we emit it now. + _q_emitUpdated(); + } + + // Immediately dispatch all pending update requests on the views. + for (int i = 0; i < views.size(); ++i) { + QWidget *viewport = views.at(i)->d_func()->viewport; + if (qt_widget_private(viewport)->paintOnScreen()) + QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest); + else + QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest); + } } /*! \internal Schedules an item for removal. This function leaves some stale indexes - around in the BSP tree; these will be cleaned up the next time someone - triggers purgeRemovedItems(). + around in the BSP tree if called from the item's destructor; these will + be cleaned up the next time someone triggers purgeRemovedItems(). - Note: This function is called from QGraphicsItem's destructor. \a item is + Note: This function might get called from QGraphicsItem's destructor. \a item is being destroyed, so we cannot call any pure virtual functions on it (such as boundingRect()). Also, it is unnecessary to update the item's own state in any way. - - ### Refactoring: This function shares much functionality with removeItem() */ -void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) +void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item) { Q_Q(QGraphicsScene); - // Clear focus on the item to remove any reference in the focusWidget - // chain. + // Clear focus on the item to remove any reference in the focusWidget chain. item->clearFocus(); - - int index = item->d_func()->index; - if (index != -1) { - // Important: The index is useless until purgeRemovedItems() is - // called. - indexedItems[index] = (QGraphicsItem *)0; - if (!purgePending) { + markDirty(item, QRectF(), false, false, false, false, /*removingItemFromScene=*/true); + + if (!item->d_ptr->inDestructor) { + // Can potentially call item->boundingRect() (virtual function), that's why + // we only can call this function if the item is not in its destructor. + removeFromIndex(item); + } else if (item->d_ptr->index != -1) { + // Important: The index is useless until purgeRemovedItems() is called. + indexedItems[item->d_ptr->index] = (QGraphicsItem *)0; + if (!purgePending) purgePending = true; - q->update(); - } removedItems << item; } else { // Recently added items are purged immediately. unindexedItems() never // contains stale items. unindexedItems.removeAll(item); - q->update(); + } + + if (!item->d_ptr->inDestructor && item == tabFocusFirst) { + QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item); + widget->d_func()->fixFocusChainBeforeReparenting(0, 0); + } + + item->d_func()->scene = 0; + + // Remove from parent, or unregister from toplevels. + if (QGraphicsItem *parentItem = item->parentItem()) { + if (parentItem->scene()) { + Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem", + "Parent item's scene is different from this item's scene"); + item->d_ptr->setParentItemHelper(0); + } + } else { + unregisterTopLevelItem(item); + } + + if (!item->d_ptr->inDestructor) { + // Remove from our item lists. + int index = item->d_func()->index; + if (index != -1) { + freeItemIndexes << index; + indexedItems[index] = 0; + } else { + unindexedItems.removeAll(item); + } } // Reset the mouse grabber and focus item data. @@ -763,10 +790,10 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) // Update selected & hovered item bookkeeping selectedItems.remove(item); hoverItems.removeAll(item); - pendingUpdateItems.removeAll(item); cachedItemsUnderMouse.removeAll(item); unpolishedItems.removeAll(item); - dirtyItems.removeAll(item); + pendingUpdateItems.removeAll(item); + resetDirtyItem(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin(); @@ -777,20 +804,19 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) ++iterator; } - // Remove from scene transform cache - int transformIndex = item->d_func()->sceneTransformIndex; - if (transformIndex != -1) { - validTransforms.setBit(transformIndex, 0); - freeSceneTransformSlots.append(transformIndex); + if (!item->d_ptr->inDestructor) { + // Remove all children recursively + for (int i = 0; i < item->d_ptr->children.size(); ++i) + q->removeItem(item->d_ptr->children.at(i)); } - // Reset the mouse grabber + // Reset the mouse grabber and focus item data. if (mouseGrabberItems.contains(item)) - ungrabMouse(item, /* item is dying */ true); + ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor); // Reset the keyboard grabber if (keyboardGrabberItems.contains(item)) - ungrabKeyboard(item, /* item is dying */ true); + ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor); // Reset the last mouse grabber item if (item == lastMouseGrabberItem) @@ -809,8 +835,6 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) */ void QGraphicsScenePrivate::purgeRemovedItems() { - Q_Q(QGraphicsScene); - if (!purgePending && removedItems.isEmpty()) return; @@ -826,9 +850,6 @@ void QGraphicsScenePrivate::purgeRemovedItems() freeItemIndexes << i; } purgePending = false; - - // No locality info for the items; update the whole scene. - q->update(); } /*! @@ -836,13 +857,13 @@ void QGraphicsScenePrivate::purgeRemovedItems() Starts or restarts the timer used for reindexing unindexed items. */ -void QGraphicsScenePrivate::startIndexTimer() +void QGraphicsScenePrivate::startIndexTimer(int interval) { Q_Q(QGraphicsScene); if (indexTimerId) { restartIndexTimer = true; } else { - indexTimerId = q->startTimer(QGRAPHICSSCENE_INDEXTIMER_TIMEOUT); + indexTimerId = q->startTimer(interval); } } @@ -1406,6 +1427,109 @@ QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) return 0; } +void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF rect, + QList<QGraphicsItem *> *items, + const QTransform &parentTransform, + const QTransform &viewTransform, + Qt::ItemSelectionMode mode, Qt::SortOrder order, + qreal parentOpacity) const +{ + // Calculate opacity. + qreal opacity; + if (item) { + if (!item->d_ptr->visible) + return; + QGraphicsItem *p = item->d_ptr->parent; + bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity; + bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)); + if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) { + opacity = parentOpacity * item->opacity(); + } else { + opacity = item->d_ptr->opacity; + } + if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + return; + } else { + opacity = parentOpacity; + } + + // Calculate the full transform for this item. + QTransform transform = parentTransform; + bool keep = false; + if (item) { + item->d_ptr->combineTransformFromParent(&transform, &viewTransform); + + // ### This does not take the clip into account. + QRectF brect = item->boundingRect(); + _q_adjustRect(&brect); + + keep = true; + if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) + keep = rect.contains(transform.mapRect(brect)) && rect != brect; + else + keep = rect.intersects(transform.mapRect(brect)); + + if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { + QPainterPath rectPath; + rectPath.addRect(rect); + keep = itemCollidesWithPath(item, transform.inverted().map(rectPath), mode); + } + } + + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); + bool dontProcessItem = !item || !keep; + bool dontProcessChildren = item && dontProcessItem && childClip; + + // Find and sort children. + QList<QGraphicsItem *> &children = item ? item->d_ptr->children : const_cast<QGraphicsScenePrivate *>(this)->topLevelItems; + if (!dontProcessChildren) { + if (item && item->d_ptr->needSortChildren) { + item->d_ptr->needSortChildren = 0; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } else if (!item && needSortTopLevelItems) { + const_cast<QGraphicsScenePrivate *>(this)->needSortTopLevelItems = false; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } + } + + childClip &= !dontProcessChildren & !children.isEmpty(); + + // Clip. + if (childClip) + rect &= transform.map(item->shape()).controlPointRect(); + + // Process children behind + int i = 0; + if (!dontProcessChildren) { + for (i = 0; i < children.size(); ++i) { + QGraphicsItem *child = children.at(i); + if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) + break; + recursive_items_helper(child, rect, items, transform, viewTransform, + mode, order, opacity); + } + } + + // Process item + if (!dontProcessItem) + items->append(item); + + // Process children in front + if (!dontProcessChildren) { + for (; i < children.size(); ++i) + recursive_items_helper(children.at(i), rect, items, transform, viewTransform, + mode, order, opacity); + } + + if (!item && order == Qt::AscendingOrder) { + int n = items->size(); + for (int i = 0; i < n / 2; ++i) { + QGraphicsItem *tmp = (*items)[n - i - 1]; + (*items)[n - i - 1] = (*items)[i]; + (*items)[i] = tmp; + } + } +} QList<QGraphicsItem *> QGraphicsScenePrivate::items_helper(const QPointF &pos) const { @@ -1641,7 +1765,7 @@ void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items, QList<QGraphicsItem *> &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items and all their children. @@ -1681,7 +1805,7 @@ void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items, QList<QGraphicsItem *> &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items and all their children. @@ -1717,7 +1841,7 @@ void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items, if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) { // Recurse into children. - if (!item->d_ptr->hasTransform || item->transform().type() <= QTransform::TxScale) { + if (!item->d_ptr->transformData || item->d_ptr->transformData->computedFullTransform().type() <= QTransform::TxScale) { // Rect childItems_helper(items, item, item->mapRectFromParent(rect), mode); } else { @@ -1747,7 +1871,7 @@ void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items, QList<QGraphicsItem *> &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items. @@ -1806,7 +1930,7 @@ void QGraphicsScenePrivate::childItems_helper(QList<QGraphicsItem *> *items, QList<QGraphicsItem *> &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items. @@ -1870,7 +1994,12 @@ inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item if (f1 != f2) return f2; qreal z1 = d1->z; qreal z2 = d2->z; - return z1 != z2 ? z1 > z2 : d1->siblingIndex > d2->siblingIndex; + return z1 > z2; +} + +static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2) +{ + return qt_closestLeaf(item2, item1); } /*! @@ -2483,7 +2612,6 @@ QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const return d->items_helper(pos); } - /*! \fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const @@ -2500,7 +2628,9 @@ QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos) const QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const { Q_D(const QGraphicsScene); - return d->items_helper(rect, mode, Qt::AscendingOrder); + QList<QGraphicsItem *> itemList; + d->recursive_items_helper(0, rect, &itemList, QTransform(), QTransform(), mode, Qt::AscendingOrder); + return itemList; } /*! @@ -2899,7 +3029,7 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // a temporary list and schedule an indexing for later. d->unindexedItems << item; item->d_func()->index = -1; - d->startIndexTimer(); + d->startIndexTimer(0); // Add to list of toplevels if this item is a toplevel. if (!item->d_ptr->parent) @@ -3252,108 +3382,7 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) return; } - // If the item has focus, remove it (and any focusWidget reference). - item->clearFocus(); - - // Clear its background - item->update(); - - // Note: This will access item's sceneBoundingRect(), which (as this is - // C++) is why we cannot call removeItem() from QGraphicsItem's - // destructor. - d->removeFromIndex(item); - - if (item == d->tabFocusFirst) { - QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item); - widget->d_func()->fixFocusChainBeforeReparenting(0, 0); - } - // Set the item's scene ptr to 0. - item->d_func()->scene = 0; - - // Remove from parent, or unregister from toplevels. - if (QGraphicsItem *parentItem = item->parentItem()) { - if (parentItem->scene()) { - Q_ASSERT_X(parentItem->scene() == this, "QGraphicsScene::removeItem", - "Parent item's scene is different from this item's scene"); - item->setParentItem(0); - } - } else { - d->unregisterTopLevelItem(item); - } - - // Remove from our item lists. - int index = item->d_func()->index; - if (index != -1) { - d->freeItemIndexes << index; - d->indexedItems[index] = 0; - } else { - d->unindexedItems.removeAll(item); - } - - // Remove from scene transform cache - int transformIndex = item->d_func()->sceneTransformIndex; - if (transformIndex != -1) { - d->validTransforms.setBit(transformIndex, 0); - d->freeSceneTransformSlots.append(transformIndex); - item->d_func()->sceneTransformIndex = -1; - } - - if (item == d->focusItem) - d->focusItem = 0; - if (item == d->lastFocusItem) - d->lastFocusItem = 0; - if (item == d->activeWindow) { - // ### deactivate... - d->activeWindow = 0; - } - - // Disable selectionChanged() for individual items - ++d->selectionChanging; - int oldSelectedItemsSize = d->selectedItems.size(); - - // Update selected & hovered item bookkeeping - d->selectedItems.remove(item); - d->hoverItems.removeAll(item); - d->pendingUpdateItems.removeAll(item); - d->cachedItemsUnderMouse.removeAll(item); - d->unpolishedItems.removeAll(item); - d->dirtyItems.removeAll(item); - - //We remove all references of item from the sceneEventFilter arrays - QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = d->sceneEventFilters.begin(); - while (iterator != d->sceneEventFilters.end()) { - if (iterator.value() == item || iterator.key() == item) - iterator = d->sceneEventFilters.erase(iterator); - else - ++iterator; - } - - - //Ensure dirty flag have the correct default value so the next time it will be added it will receive updates - item->d_func()->dirty = 0; - item->d_func()->dirtyChildren = 0; - - // Remove all children recursively - foreach (QGraphicsItem *child, item->children()) - removeItem(child); - - // Reset the mouse grabber and focus item data. - if (d->mouseGrabberItems.contains(item)) - d->ungrabMouse(item); - - // Reset the keyboard grabber - if (d->keyboardGrabberItems.contains(item)) - item->ungrabKeyboard(); - - // Reset the last mouse grabber item - if (item == d->lastMouseGrabberItem) - d->lastMouseGrabberItem = 0; - - // Reenable selectionChanged() for individual items - --d->selectionChanging; - - if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemsSize) - emit selectionChanged(); + d->removeItemHelper(item); // Deliver post-change notification item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); @@ -3656,7 +3685,7 @@ void QGraphicsScene::update(const QRectF &rect) } } - if (!directUpdates && !d->calledEmitUpdated) { + if (!d->calledEmitUpdated) { d->calledEmitUpdated = true; QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection); } @@ -3775,6 +3804,8 @@ bool QGraphicsScene::event(QEvent *event) // items from inside event handlers, this list can quickly end up // having stale pointers in it. We need to clear it before dispatching // events that use it. + // ### this should only be cleared if we received a new mouse move event, + // which relies on us fixing the replay mechanism in QGraphicsView. d->cachedItemsUnderMouse.clear(); default: break; @@ -4918,7 +4949,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte // Generate the item's exposedRect and map its list of expose // rects to device coordinates. - QStyleOptionGraphicsItem cacheOption = *option; + styleOptionTmp = *option; QRegion pixmapExposed; QRectF exposedRect; if (!itemCache->allExposed) { @@ -4930,11 +4961,11 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } else { exposedRect = brect; } - cacheOption.exposedRect = exposedRect; + styleOptionTmp.exposedRect = exposedRect; // Render. _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(), - &cacheOption, painterStateProtection); + &styleOptionTmp, painterStateProtection); // insert this pixmap into the cache. itemCache->key = QPixmapCache::insert(pix); @@ -5095,12 +5126,12 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte foreach (QRect r, scrollExposure.rects()) br |= pixmapToItem.mapRect(r); } - QStyleOptionGraphicsItem cacheOption = *option; - cacheOption.exposedRect = br.adjusted(-1, -1, 1, 1); + styleOptionTmp = *option; + styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1); // Render the exposed areas. _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(), - &cacheOption, painterStateProtection); + &styleOptionTmp, painterStateProtection); // Reset expose data. pixModified = true; @@ -5129,6 +5160,392 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } } +void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, + const QTransform &viewTransform, + QRegion *exposedRegion, QWidget *widget, + QList<QGraphicsItem *> *topLevelItems, + qreal parentOpacity) +{ + // Calculate opacity. + qreal opacity; + bool invisibleButChildIgnoresParentOpacity = false; + if (item) { + if (!item->d_ptr->visible) + return; + QGraphicsItem *p = item->d_ptr->parent; + bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity; + bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)); + if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) { + opacity = parentOpacity * item->opacity(); + } else { + opacity = item->d_ptr->opacity; + } + if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { + invisibleButChildIgnoresParentOpacity = !item->d_ptr->childrenCombineOpacity(); + if (!invisibleButChildIgnoresParentOpacity) + return; + } + } else { + opacity = parentOpacity; + } + + // Calculate the full transform for this item. + QRect viewBoundingRect; + bool wasDirtyParentSceneTransform = false; + QTransform transform; + if (item) { + if (item->d_ptr->itemIsUntransformable()) { + transform = item->deviceTransform(viewTransform); + } else { + if (item->d_ptr->dirtySceneTransform) { + item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform + : QTransform(); + item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform); + item->d_ptr->dirtySceneTransform = 0; + wasDirtyParentSceneTransform = true; + } + transform = item->d_ptr->sceneTransform; + transform *= viewTransform; + } + + QRectF brect = item->boundingRect(); + // ### This does not take the clip into account. + _q_adjustRect(&brect); + viewBoundingRect = transform.mapRect(brect).toRect(); + item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); + viewBoundingRect.adjust(-1, -1, 1, 1); + if (exposedRegion) + viewBoundingRect &= exposedRegion->boundingRect(); + } + + // Find and sort children. + QList<QGraphicsItem *> tmp; + QList<QGraphicsItem *> *children = 0; + if (item) { + children = &item->d_ptr->children; + } else if (topLevelItems) { + children = topLevelItems; + } else if (indexMethod == QGraphicsScene::NoIndex || !exposedRegion) { + children = &this->topLevelItems; + } else { + QRectF sceneRect = viewTransform.inverted().mapRect(QRectF(exposedRegion->boundingRect().adjusted(-1, -1, 1, 1))); + if (!largestUntransformableItem.isEmpty()) { + // ### Nuke this when we move the indexing code into a separate + // class. All the largestUntransformableItem code should then go + // away, and the estimate function should return untransformable + // items as well. + QRectF untr = largestUntransformableItem; + QRectF ltri = viewTransform.inverted().mapRect(untr); + ltri.adjust(-untr.width(), -untr.height(), untr.width(), untr.height()); + sceneRect.adjust(-ltri.width(), -ltri.height(), ltri.width(), ltri.height()); + } + tmp = estimateItemsInRect(sceneRect); + + QList<QGraphicsItem *> tli; + for (int i = 0; i < tmp.size(); ++i) + tmp.at(i)->topLevelItem()->d_ptr->itemDiscovered = 1; + + // Sort if the toplevel list is unsorted. + if (needSortTopLevelItems) { + needSortTopLevelItems = false; + qStableSort(this->topLevelItems.begin(), + this->topLevelItems.end(), qt_notclosestLeaf); + } + + for (int i = 0; i < this->topLevelItems.size(); ++i) { + // ### Investigate smarter ways. Looping through all top level + // items is not optimal. If the BSP tree is to have maximum + // effect, it should be possible to sort the subset of items + // quickly. We must use this approach for now, as it's the only + // current way to keep the stable sorting order (insertion order). + QGraphicsItem *item = this->topLevelItems.at(i); + if (item->d_ptr->itemDiscovered) { + item->d_ptr->itemDiscovered = 0; + tli << item; + } + } + + tmp = tli; + children = &tmp; + } + + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); + bool dontDrawItem = !item || viewBoundingRect.isEmpty(); + bool dontDrawChildren = item && dontDrawItem && childClip; + childClip &= !dontDrawChildren && !children->isEmpty(); + if (item && ((item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) || invisibleButChildIgnoresParentOpacity)) + dontDrawItem = true; + + // Clip children. + if (childClip) { + painter->save(); + painter->setWorldTransform(transform); + painter->setClipPath(item->shape(), Qt::IntersectClip); + } + + if (!dontDrawChildren) { + if (item && item->d_ptr->needSortChildren) { + item->d_ptr->needSortChildren = 0; + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); + } else if (!item && needSortTopLevelItems && children != &tmp) { + needSortTopLevelItems = false; + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); + } + } + + // Draw children behind + int i = 0; + if (!dontDrawChildren) { + // ### Don't visit children that don't ignore parent opacity if this + // item is invisible. + for (i = 0; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; + if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) + break; + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, + 0, opacity); + } + } + + // Draw item + if (!dontDrawItem) { + item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); + + bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); + bool savePainter = clipsToShape || painterStateProtection; + if (savePainter) + painter->save(); + if (!childClip) + painter->setWorldTransform(transform); + if (clipsToShape) + painter->setClipPath(item->shape(), Qt::IntersectClip); + painter->setOpacity(opacity); + drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection); + + if (savePainter) + painter->restore(); + } + + // Draw children in front + if (!dontDrawChildren) { + // ### Don't visit children that don't ignore parent opacity if this + // item is invisible. + for (; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, + widget, 0, opacity); + } + } else if (wasDirtyParentSceneTransform) { + item->d_ptr->invalidateChildrenSceneTransform(); + } + + // Restore child clip + if (childClip) + painter->restore(); +} + +void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren, + bool maybeDirtyClipPath, bool force, bool ignoreOpacity, + bool removingItemFromScene) +{ + Q_ASSERT(item); + if (updateAll) + return; + + if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, + /*ignoreVisibleBit=*/force, + /*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren, + /*ignoreOpacity=*/ignoreOpacity)) { + return; + } + + const bool fullItemUpdate = rect.isNull(); + if (!fullItemUpdate && rect.isEmpty()) + return; + + if (!processDirtyItemsEmitted) { + QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection); + processDirtyItemsEmitted = true; + } + + if (removingItemFromScene) { + // Note that this function can be called from the item's destructor, so + // do NOT call any virtual functions on it within this block. + if ((connectedSignals & changedSignalMask) || views.isEmpty()) { + // This block of code is kept for compatibility. Since 4.5, by default + // QGraphicsView does not connect the signal and we use the below + // method of delivering updates. + q_func()->update(); + return; + } + + for (int i = 0; i < views.size(); ++i) { + QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func(); + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + } + return; + } + + item->d_ptr->dirty = 1; + if (fullItemUpdate) + item->d_ptr->fullUpdatePending = 1; + else if (!item->d_ptr->fullUpdatePending) + item->d_ptr->needsRepaint |= rect; + + if (invalidateChildren) { + item->d_ptr->allChildrenDirty = 1; + item->d_ptr->dirtyChildren = 1; + } + + QGraphicsItem *p = item->d_ptr->parent; + while (p && !p->d_ptr->dirtyChildren) { + p->d_ptr->dirtyChildren = 1; + p = p->d_ptr->parent; + } +} + +void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren) +{ + Q_Q(QGraphicsScene); + + // Calculate the full scene transform for this item. + bool wasDirtyParentSceneTransform = false; + if (item && item->d_ptr->dirtySceneTransform && !item->d_ptr->itemIsUntransformable()) { + item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform + : QTransform(); + item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform); + item->d_ptr->dirtySceneTransform = 0; + wasDirtyParentSceneTransform = true; + } + + // Process item. + bool wasDirtyParentViewBoundingRects = false; + if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) { + const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); + const bool untransformableItem = item->d_ptr->itemIsUntransformable(); + const QRectF itemBoundingRect = item->boundingRect(); + + if (item->d_ptr->geometryChanged) { + // Update growingItemsBoundingRect. + if (!hasSceneRect) { + QRectF itemSceneBoundingRect = item->d_ptr->sceneTransform.mapRect(itemBoundingRect); + _q_adjustRect(&itemSceneBoundingRect); + growingItemsBoundingRect |= itemSceneBoundingRect; + } + item->d_ptr->geometryChanged = 0; + } + + if (useCompatUpdate && !untransformableItem && qFuzzyIsNull(item->boundingRegionGranularity())) { + // This block of code is kept for compatibility. Since 4.5, by default + // QGraphicsView does not connect the signal and we use the below + // method of delivering updates. + q->update(item->d_ptr->sceneTransform.mapRect(itemBoundingRect)); + } else { + QRectF dirtyRect; + bool uninitializedDirtyRect = true; + + for (int j = 0; j < views.size(); ++j) { + QGraphicsView *view = views.at(j); + QGraphicsViewPrivate *viewPrivate = view->d_func(); + if (viewPrivate->fullUpdatePending) + continue; + switch (viewPrivate->viewportUpdateMode) { + case QGraphicsView::NoViewportUpdate: + continue; + case QGraphicsView::FullViewportUpdate: + view->viewport()->update(); + viewPrivate->fullUpdatePending = 1; + continue; + default: + break; + } + + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) { + wasDirtyParentViewBoundingRects = true; + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + } + + if (!item->d_ptr->dirty) + continue; + + if (uninitializedDirtyRect) { + dirtyRect = itemBoundingRect; + _q_adjustRect(&dirtyRect); + if (!item->d_ptr->fullUpdatePending) { + _q_adjustRect(&item->d_ptr->needsRepaint); + dirtyRect &= item->d_ptr->needsRepaint; + } + uninitializedDirtyRect = false; + } + + if (dirtyRect.isEmpty()) + continue; // Discard updates outside the bounding rect. + + QTransform deviceTransform = item->d_ptr->sceneTransform; + if (view->isTransformed()) { + if (!untransformableItem) + deviceTransform *= view->viewportTransform(); + else + deviceTransform = item->deviceTransform(view->viewportTransform()); + } + if (item->d_ptr->hasBoundingRegionGranularity) + viewPrivate->updateRegion(deviceTransform.map(QRegion(dirtyRect.toRect()))); + else + viewPrivate->updateRect(deviceTransform.mapRect(dirtyRect).toRect()); + } + } + } + + // Process root items / children. + if (!item || item->d_ptr->dirtyChildren) { + QList<QGraphicsItem *> *children = item ? &item->d_ptr->children : &topLevelItems; + const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty; + if (!dirtyAncestorContainsChildren) { + dirtyAncestorContainsChildren = item && item->d_ptr->fullUpdatePending + && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape); + } + for (int i = 0; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; + if (wasDirtyParentViewBoundingRects) + child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1; + + if (allChildrenDirty) { + child->d_ptr->dirty = 1; + child->d_ptr->fullUpdatePending = 1; + child->d_ptr->dirtyChildren = 1; + child->d_ptr->allChildrenDirty = 1; + } else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) { + resetDirtyItem(child); + continue; + } + + if (dirtyAncestorContainsChildren || updateAll) { + // No need to process this child's dirty rect, hence reset the dirty state. + // However, we have to continue the recursion because it might have a dirty + // view bounding rect that needs repaint. We also have to reset the dirty + // state of its descendants. + child->d_ptr->dirty = 0; + child->d_ptr->fullUpdatePending = 0; + if (updateAll) + child->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; + } + + processDirtyItemsRecursive(child, dirtyAncestorContainsChildren); + } + } else if (wasDirtyParentSceneTransform) { + item->d_ptr->invalidateChildrenSceneTransform(); + } + + if (item) + resetDirtyItem(item); +} + /*! Paints the given \a items using the provided \a painter, after the background has been drawn, and before the foreground has been @@ -5160,111 +5577,29 @@ void QGraphicsScene::drawItems(QPainter *painter, const QStyleOptionGraphicsItem options[], QWidget *widget) { Q_D(QGraphicsScene); - - // Detect if painter state protection is disabled. QTransform viewTransform = painter->worldTransform(); - QVarLengthArray<QGraphicsItem *, 16> childClippers; - - for (int i = 0; i < numItems; ++i) { - QGraphicsItem *item = items[i]; - if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) { - if (!childClippers.isEmpty()) { - // Item is not clipped to any ancestor: pop all current clippers. - for (int i = 0; i < childClippers.size(); ++i) - painter->restore(); - childClippers.clear(); - } - } else { - // Item is clipped to an ancestor, which may or may not be in our - // child clipper list. Let's start by finding the item's closest - // clipping ancestor. - QGraphicsItem *clipParent = item->parentItem(); - while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) - clipParent = clipParent->parentItem(); - - // Pop any in-between clippers. If the clipper is unknown, pop - // them all. ### QVarLengthArray::lastIndexOf(). - int index = -1; - for (int n = childClippers.size() - 1; n >= 0; --n) { - if (childClippers[n] == clipParent) { - index = n; - break; - } - } - if (index != -1) { - int toPop = childClippers.size() - index - 1; - if (toPop > 0) { - for (int i = 0; i < toPop; ++i) - painter->restore(); - childClippers.resize(index + 1); - } - } - - // Sanity check - if (!childClippers.isEmpty()) - Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent); - - // If the clipper list is empty at this point, but we're still - // clipped to an ancestor, then we need to build the clip chain - // ourselves. There is only one case that can produce this issue: - // This item is stacked behind an ancestor: - // ItemStacksBehindParent. - if (childClippers.isEmpty()) { - Q_ASSERT(clipParent != 0); - // Build a stack of clippers. - QVarLengthArray<QGraphicsItem *, 16> clippers; - QGraphicsItem *p = clipParent; - do { - if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) - clippers.append(p); - } while ((p = p->parentItem()) && (p->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)); - - // ### This code path can also use the itemTransform - // optimization, but it's hit very rarely. - for (int i = clippers.size() - 1; i >= 0; --i) { - QGraphicsItem *clipper = clippers[i]; - painter->setWorldTransform(clipper->deviceTransform(viewTransform), false); - - childClippers.append(clipper); - painter->save(); - painter->setClipPath(clipper->shape(), Qt::IntersectClip); - } - Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent); - } - } + Q_UNUSED(options); - // Set up the painter transform - painter->setWorldTransform(item->deviceTransform(viewTransform), false); - - // Save painter - bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape)); - if (saveState) - painter->save(); - - // Set local clip - if (item->flags() & QGraphicsItem::ItemClipsToShape) - painter->setClipPath(item->shape(), Qt::IntersectClip); - - // Setup opacity - painter->setOpacity(item->effectiveOpacity()); - - // Draw the item - d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection); - - if (saveState) - painter->restore(); + // Determine view, expose and flags. + QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0; + QRegion *expose = 0; + if (view) + expose = &view->d_func()->exposedRegion; - if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape) { - // Clip descendents to this item's shape, and keep the painter - // saved. - childClippers.append(item); - painter->save(); - painter->setClipPath(item->shape(), Qt::IntersectClip); + // Find all toplevels, they are already sorted. + QList<QGraphicsItem *> topLevelItems; + for (int i = 0; i < numItems; ++i) { + QGraphicsItem *item = items[i]->topLevelItem(); + if (!item->d_ptr->itemDiscovered) { + topLevelItems << item; + item->d_ptr->itemDiscovered = 1; + d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget); } } - for (int i = 0; i < childClippers.size(); ++i) - painter->restore(); + // Reset discovery bits. + for (int i = 0; i < topLevelItems.size(); ++i) + topLevelItems.at(i)->d_ptr->itemDiscovered = 0; painter->setWorldTransform(viewTransform); } @@ -5376,73 +5711,6 @@ bool QGraphicsScene::focusNextPrevChild(bool next) */ /*! - \internal - - This private function is called by QGraphicsItem, which is a friend of - QGraphicsScene. It is used by QGraphicsScene to record the rectangles that - need updating. It also launches a single-shot timer to ensure that - updated() will be emitted later. - - The \a item parameter is the item that changed, and \a rect is the - area of the item that changed given in item coordinates. -*/ -void QGraphicsScene::itemUpdated(QGraphicsItem *item, const QRectF &rect) -{ - Q_D(QGraphicsScene); - // Deliver the actual update. - if (!d->updateAll) { - if (d->views.isEmpty() || ((d->connectedSignals & d->changedSignalMask) && !item->d_ptr->itemIsUntransformable() - && qFuzzyIsNull(item->boundingRegionGranularity()))) { - // This block of code is kept for compatibility. Since 4.5, by default - // QGraphicsView does not connect the signal and we use the below - // method of delivering updates. - update(item->sceneBoundingRect()); - } else { - // ### Remove _q_adjustedRects(). - QRectF boundingRect(adjustedItemBoundingRect(item)); - if (!rect.isNull()) { - QRectF adjustedRect(rect); - _q_adjustRect(&adjustedRect); - boundingRect &= adjustedRect; - } - - // Update each view directly. - for (int i = 0; i < d->views.size(); ++i) - d->views.at(i)->d_func()->itemUpdated(item, boundingRect); - } - } - if (item->d_ptr->dirty) { - d->dirtyItems << item; - d->resetDirtyItemsLater(); - } - - if (!item->isVisible()) - return; // Hiding an item won't effect the largestUntransformableItem/sceneRect. - - // Update d->largestUntransformableItem by mapping this item's bounding - // rect back to the topmost untransformable item's untransformed - // coordinate system (which sort of equals the 1:1 coordinate system of an - // untransformed view). - if (item->d_ptr->itemIsUntransformable()) { - QGraphicsItem *parent = item; - while (parent && (parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations)) - parent = parent->parentItem(); - d->largestUntransformableItem |= item->mapToItem(parent, item->boundingRect()).boundingRect(); - } - - // Only track the automatically growing scene rect if the scene has no - // defined scene rect. - if (!d->hasSceneRect) { - QRectF oldGrowingItemsBoundingRect = d->growingItemsBoundingRect; - QRectF adjustedItemSceneBoundingRect(item->sceneBoundingRect()); - _q_adjustRect(&adjustedItemSceneBoundingRect); - d->growingItemsBoundingRect |= adjustedItemSceneBoundingRect; - if (d->growingItemsBoundingRect != oldGrowingItemsBoundingRect) - emit sceneRectChanged(d->growingItemsBoundingRect); - } -} - -/*! \since 4.4 Returns the scene's style, or the same as QApplication::style() if the diff --git a/src/gui/graphicsview/qgraphicsscene.h b/src/gui/graphicsview/qgraphicsscene.h index a76b348..db93666 100644 --- a/src/gui/graphicsview/qgraphicsscene.h +++ b/src/gui/graphicsview/qgraphicsscene.h @@ -273,17 +273,14 @@ Q_SIGNALS: void selectionChanged(); private: - void itemUpdated(QGraphicsItem *item, const QRectF &rect); - Q_DECLARE_PRIVATE(QGraphicsScene) Q_DISABLE_COPY(QGraphicsScene) Q_PRIVATE_SLOT(d_func(), void _q_updateIndex()) Q_PRIVATE_SLOT(d_func(), void _q_emitUpdated()) - Q_PRIVATE_SLOT(d_func(), void _q_removeItemLater(QGraphicsItem *item)) Q_PRIVATE_SLOT(d_func(), void _q_updateLater()) Q_PRIVATE_SLOT(d_func(), void _q_polishItems()) Q_PRIVATE_SLOT(d_func(), void _q_updateSortCache()) - Q_PRIVATE_SLOT(d_func(), void _q_resetDirtyItems()) + Q_PRIVATE_SLOT(d_func(), void _q_processDirtyItems()) friend class QGraphicsItem; friend class QGraphicsItemPrivate; friend class QGraphicsView; diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index f90bb8f..bd312a1 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -58,6 +58,7 @@ #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW #include "qgraphicssceneevent.h" +#include "qgraphicsview.h" #include "qgraphicsscene_bsp_p.h" #include "qgraphicsitem_p.h" @@ -69,6 +70,9 @@ #include <QtGui/qfont.h> #include <QtGui/qpalette.h> #include <QtGui/qstyle.h> +#include <QtGui/qstyleoption.h> + +static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; QT_BEGIN_NAMESPACE @@ -106,31 +110,30 @@ public: QList<QRectF> updatedRects; bool updateAll; bool calledEmitUpdated; + bool processDirtyItemsEmitted; QPainterPath selectionArea; int selectionChanging; QSet<QGraphicsItem *> selectedItems; QList<QGraphicsItem *> unindexedItems; QList<QGraphicsItem *> indexedItems; - QList<QGraphicsItem *> dirtyItems; QList<QGraphicsItem *> pendingUpdateItems; QList<QGraphicsItem *> unpolishedItems; QList<QGraphicsItem *> topLevelItems; + bool needSortTopLevelItems; QMap<QGraphicsItem *, QPointF> movingItemsInitialPositions; void registerTopLevelItem(QGraphicsItem *item); void unregisterTopLevelItem(QGraphicsItem *item); void _q_updateLater(); void _q_polishItems(); - void _q_resetDirtyItems(); - void resetDirtyItemsLater(); - bool dirtyItemResetPending; + void _q_processDirtyItems(); QList<int> freeItemIndexes; bool regenerateIndex; bool purgePending; - void _q_removeItemLater(QGraphicsItem *item); + void removeItemHelper(QGraphicsItem *item); QSet<QGraphicsItem *> removedItems; void purgeRemovedItems(); @@ -139,7 +142,7 @@ public: int indexTimerId; bool restartIndexTimer; - void startIndexTimer(); + void startIndexTimer(int interval = QGRAPHICSSCENE_INDEXTIMER_TIMEOUT); bool stickyFocus; bool hasFocus; @@ -208,6 +211,10 @@ public: void mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent); QGraphicsWidget *windowForItem(const QGraphicsItem *item) const; + void recursive_items_helper(QGraphicsItem *item, QRectF rect, QList<QGraphicsItem *> *items, + const QTransform &parentTransform, const QTransform &viewTransform, + Qt::ItemSelectionMode mode, Qt::SortOrder order, qreal parentOpacity = 1.0) const; + QList<QGraphicsItem *> items_helper(const QPointF &pos) const; QList<QGraphicsItem *> items_helper(const QRectF &rect, Qt::ItemSelectionMode mode, @@ -257,6 +264,26 @@ public: void drawItemHelper(QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget, bool painterStateProtection); + + void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, + QRegion *exposedRegion, QWidget *widget, + QList<QGraphicsItem *> *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); + void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, + bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false, + bool removingItemFromScene = false); + void processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren = false); + + inline void resetDirtyItem(QGraphicsItem *item) + { + Q_ASSERT(item); + item->d_ptr->dirty = 0; + item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; + item->d_ptr->geometryChanged = 0; + item->d_ptr->dirtyChildren = 0; + item->d_ptr->needsRepaint = QRectF(); + item->d_ptr->allChildrenDirty = 0; + item->d_ptr->fullUpdatePending = 0; + } QStyle *style; QFont font; @@ -268,6 +295,8 @@ public: void resolvePalette(); void updatePalette(const QPalette &palette); + QStyleOptionGraphicsItem styleOptionTmp; + // items with gestures -> list of started gestures. QMap<QGraphicsItem*, QSet<QGesture*> > itemsWithGestures; QSet<int> grabbedGestures; @@ -275,10 +304,6 @@ public: void releaseGesture(QGraphicsItem *item, int gestureId); void sendGestureEvent(const QSet<QGesture*> &gestures, const QSet<QString> &cancelled); - mutable QVector<QTransform> sceneTransformCache; - mutable QBitArray validTransforms; - mutable QVector<int> freeSceneTransformSlots; - QMap<int, QGraphicsSceneTouchEvent::TouchPoint> sceneCurrentTouchPoints; QHash<int, QGraphicsItem *> itemForTouchPointId; static void updateTouchPointsForItem(QGraphicsItem *item, QGraphicsSceneTouchEvent *touchEvent); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index e874071..521ef7f 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 @@ -363,8 +361,6 @@ QGraphicsViewPrivate::QGraphicsViewPrivate() #endif lastDragDropEvent(0), fullUpdatePending(true), - dirtyRectCount(0), - updatingLater(false), updateSceneSlotReimplementedChecked(false) { styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS); @@ -784,12 +780,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) + if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); @@ -821,7 +818,7 @@ 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(); } @@ -838,125 +835,28 @@ static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item) 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() +void QGraphicsViewPrivate::processPendingUpdates() { - Q_Q(QGraphicsView); - if (updatingLater) - return; - updatingLater = true; - QMetaObject::invokeMethod(q, "_q_updateLaterSlot", Qt::QueuedConnection); -} - -void QGraphicsViewPrivate::_q_updateLaterSlot() -{ - 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); + if (fullUpdatePending) { // We have already called viewport->update() + dirtyBoundingRect = QRect(); + dirtyRegion = QRegion(); + return; } - 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 (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + viewport->update(dirtyBoundingRect); + 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() @@ -964,14 +864,13 @@ void QGraphicsViewPrivate::updateAll() Q_Q(QGraphicsView); q->viewport()->update(); fullUpdatePending = true; - dirtyRectCount = 0; dirtyBoundingRect = QRect(); - updatingLater = false; + dirtyRegion = QRegion(); } void QGraphicsViewPrivate::updateRegion(const QRegion &r) { - if (r.isEmpty()) + if (r.isEmpty() || fullUpdatePending) return; Q_Q(QGraphicsView); @@ -984,45 +883,30 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r.boundingRect(); - if (dirtyBoundingRect == q->viewport()->rect()) { + if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; q->viewport()->update(); - } else { - updateLater(); } 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(); + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) { + dirtyRegion += r; + } else { + const QVector<QRect> &rects = r.rects(); + for (int i = 0; i < rects.size(); ++i) + dirtyRegion += rects.at(i).adjusted(-2, -2, 2, 2); + } break; case QGraphicsView::NoViewportUpdate: // Unreachable 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; - } } void QGraphicsViewPrivate::updateRect(const QRect &r) { - if (r.isEmpty()) + if (r.isEmpty() || fullUpdatePending) return; Q_Q(QGraphicsView); @@ -1035,22 +919,17 @@ void QGraphicsViewPrivate::updateRect(const QRect &r) break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r; - if (dirtyBoundingRect == q->viewport()->rect()) { + if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; q->viewport()->update(); - } else { - updateLater(); } 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; + else + dirtyRegion += r.adjusted(-2, -2, 2, 2); break; case QGraphicsView::NoViewportUpdate: // Unreachable @@ -2647,9 +2526,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) @@ -3433,12 +3314,12 @@ void QGraphicsView::paintEvent(QPaintEvent *event) d->scene->d_func()->painterStateProtection = !(d->optimizationFlags & DontSavePainterState); // Determine the exposed region - QRegion exposedRegion = event->region(); + d->exposedRegion = event->region(); if (!d->accelerateScrolling) - exposedRegion = viewport()->rect(); + d->exposedRegion = viewport()->rect(); else if (d->viewportUpdateMode == BoundingRectViewportUpdate) - exposedRegion = event->rect(); - QRectF exposedSceneRect = mapToScene(exposedRegion.boundingRect()).boundingRect(); + d->exposedRegion = event->rect(); + QRectF exposedSceneRect = mapToScene(d->exposedRegion.boundingRect()).boundingRect(); // Set up the painter QPainter painter(viewport()); @@ -3455,20 +3336,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) 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 - + // Draw background if ((d->cacheMode & CacheBackground) #ifdef Q_WS_X11 && X11->use_xrender @@ -3510,33 +3378,31 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.restore(); } -#ifdef QGRAPHICSVIEW_DEBUG - int backgroundTime = stopWatch.elapsed() - exposedTime; -#endif - - 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, exposedRegion, allItems); - // Draw the items. - drawItems(&painter, numItems, itemArray, styleOptionArray); - d->freeStyleOptionsArray(styleOptionArray); + // Items + if (!(d->optimizationFlags & IndirectPainting)) { + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, &d->exposedRegion, + viewport(), 0); + } else { + // Find all exposed items + bool allItems = false; + QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems); + + 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); + } } -#ifdef QGRAPHICSVIEW_DEBUG - int itemsTime = stopWatch.elapsed() - exposedTime - backgroundTime; -#endif - // Foreground drawForeground(&painter, exposedSceneRect); -#ifdef QGRAPHICSVIEW_DEBUG - int foregroundTime = stopWatch.elapsed() - exposedTime - backgroundTime - itemsTime; -#endif - #ifndef QT_NO_RUBBERBAND // Rubberband if (d->rubberBanding && !d->rubberBandRect.isEmpty()) { @@ -3558,17 +3424,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; } @@ -3615,10 +3470,7 @@ 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); + d->dirtyRegion.translate(dx, dy); if (d->accelerateScrolling) { #ifndef QT_NO_RUBBERBAND // Update new and old rubberband regions @@ -3752,8 +3604,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); + } } /*! @@ -3782,6 +3636,18 @@ QTransform QGraphicsView::viewportTransform() const } /*! + 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; diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index c3ea6e5..387fa01 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -112,7 +112,8 @@ public: enum OptimizationFlag { DontClipPainter = 0x1, // obsolete DontSavePainterState = 0x2, - DontAdjustForAntialiasing = 0x4 + DontAdjustForAntialiasing = 0x4, + IndirectPainting = 0x8 }; Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag) @@ -169,6 +170,7 @@ public: void resetMatrix(); QTransform transform() const; QTransform viewportTransform() const; + bool isTransformed() const; void setTransform(const QTransform &matrix, bool combine = false); void resetTransform(); void rotate(qreal angle); @@ -273,7 +275,6 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_setViewportCursor(const QCursor &)) Q_PRIVATE_SLOT(d_func(), void _q_unsetViewportCursor()) #endif - Q_PRIVATE_SLOT(d_func(), void _q_updateLaterSlot()) friend class QGraphicsSceneWidget; friend class QGraphicsScene; friend class QGraphicsScenePrivate; diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index da1ca14..a54ccf0 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -159,19 +159,15 @@ public: QRect mapToViewRect(const QGraphicsItem *item, const QRectF &rect) const; QRegion mapToViewRegion(const QGraphicsItem *item, const QRectF &rect) const; - void itemUpdated(QGraphicsItem *item, const QRectF &rect); bool fullUpdatePending; - QList<QRect> dirtyRects; - QList<QRegion> dirtyRegions; - int dirtyRectCount; + QRegion dirtyRegion; QRect dirtyBoundingRect; - void updateLater(); - bool updatingLater; - void _q_updateLaterSlot(); + void processPendingUpdates(); void updateAll(); void updateRect(const QRect &rect); void updateRegion(const QRegion ®ion); bool updateSceneSlotReimplementedChecked; + QRegion exposedRegion; QList<QGraphicsItem *> findItems(const QRegion &exposedRegion, bool *allItems) const; diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 3296aee..7314167 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -1057,6 +1057,9 @@ void QGraphicsWidget::updateGeometry() ItemParentChange both to deliver \l ParentChange events, and for managing the focus chain. + QGraphicsWidget enables the ItemSendsGeometryChanges flag by default in + order to track position changes. + \sa propertyChange() */ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) diff --git a/src/gui/graphicsview/qgraphicswidget_p.cpp b/src/gui/graphicsview/qgraphicswidget_p.cpp index a435758..557b883 100644 --- a/src/gui/graphicsview/qgraphicswidget_p.cpp +++ b/src/gui/graphicsview/qgraphicswidget_p.cpp @@ -77,7 +77,9 @@ void QGraphicsWidgetPrivate::init(QGraphicsItem *parentItem, Qt::WindowFlags wFl resolveLayoutDirection(); q->unsetWindowFrameMargins(); q->setFlag(QGraphicsItem::ItemUsesExtendedStyleOption); + q->setFlag(QGraphicsItem::ItemSendsGeometryChanges); } + qreal QGraphicsWidgetPrivate::titleBarHeight(const QStyleOptionTitleBar &options) const { Q_Q(const QGraphicsWidget); |