Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qgraphicsscene.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5/*!
6 \class QGraphicsScene
7 \brief The QGraphicsScene class provides a surface for managing a large
8 number of 2D graphical items.
9 \since 4.2
10 \ingroup graphicsview-api
11 \inmodule QtWidgets
12
13 The class serves as a container for QGraphicsItems. It is used together
14 with QGraphicsView for visualizing graphical items, such as lines,
15 rectangles, text, or even custom items, on a 2D surface. QGraphicsScene is
16 part of the \l{Graphics View Framework}.
17
18 QGraphicsScene also provides functionality that lets you efficiently
19 determine both the location of items, and for determining what items are
20 visible within an arbitrary area on the scene. With the QGraphicsView
21 widget, you can either visualize the whole scene, or zoom in and view only
22 parts of the scene.
23
24 Example:
25
26 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 0
27
28 Note that QGraphicsScene has no visual appearance of its own; it only
29 manages the items. You need to create a QGraphicsView widget to visualize
30 the scene.
31
32 To add items to a scene, you start off by constructing a QGraphicsScene
33 object. Then, you have two options: either add your existing QGraphicsItem
34 objects by calling addItem(), or you can call one of the convenience
35 functions addEllipse(), addLine(), addPath(), addPixmap(), addPolygon(),
36 addRect(), or addText(), which all return a pointer to the newly added item.
37 The dimensions of the items added with these functions are relative to the
38 item's coordinate system, and the items position is initialized to (0,
39 0) in the scene.
40
41 You can then visualize the scene using QGraphicsView. When the scene
42 changes, (e.g., when an item moves or is transformed) QGraphicsScene
43 emits the changed() signal. To remove an item, call removeItem().
44
45 QGraphicsScene uses an indexing algorithm to manage the location of items
46 efficiently. By default, a BSP (Binary Space Partitioning) tree is used; an
47 algorithm suitable for large scenes where most items remain static (i.e.,
48 do not move around). You can choose to disable this index by calling
49 setItemIndexMethod(). For more information about the available indexing
50 algorithms, see the itemIndexMethod property.
51
52 The scene's bounding rect is set by calling setSceneRect(). Items can be
53 placed at any position on the scene, and the size of the scene is by
54 default unlimited. The scene rect is used only for internal bookkeeping,
55 maintaining the scene's item index. If the scene rect is unset,
56 QGraphicsScene will use the bounding area of all items, as returned by
57 itemsBoundingRect(), as the scene rect. However, itemsBoundingRect() is a
58 relatively time consuming function, as it operates by collecting
59 positional information for every item on the scene. Because of this, you
60 should always set the scene rect when operating on large scenes.
61
62 One of QGraphicsScene's greatest strengths is its ability to efficiently
63 determine the location of items. Even with millions of items on the scene,
64 the items() functions can determine the location of an item within a few
65 milliseconds. There are several overloads to items(): one that finds items
66 at a certain position, one that finds items inside or intersecting with a
67 polygon or a rectangle, and more. The list of returned items is sorted by
68 stacking order, with the topmost item being the first item in the list.
69 For convenience, there is also an itemAt() function that returns the
70 topmost item at a given position.
71
72 QGraphicsScene maintains selection information for the scene. To select
73 items, call setSelectionArea(), and to clear the current selection, call
74 clearSelection(). Call selectedItems() to get the list of all selected
75 items.
76
77 \section1 Event Handling and Propagation
78
79 Another responsibility that QGraphicsScene has, is to propagate events
80 from QGraphicsView. To send an event to a scene, you construct an event
81 that inherits QEvent, and then send it using, for example,
82 QCoreApplication::sendEvent(). event() is responsible for dispatching
83 the event to the individual items. Some common events are handled by
84 convenience event handlers. For example, key press events are handled by
85 keyPressEvent(), and mouse press events are handled by mousePressEvent().
86
87 Key events are delivered to the \e {focus item}. To set the focus item,
88 you can either call setFocusItem(), passing an item that accepts focus, or
89 the item itself can call QGraphicsItem::setFocus(). Call focusItem() to
90 get the current focus item. For compatibility with widgets, the scene also
91 maintains its own focus information. By default, the scene does not have
92 focus, and all key events are discarded. If setFocus() is called, or if an
93 item on the scene gains focus, the scene automatically gains focus. If the
94 scene has focus, hasFocus() will return true, and key events will be
95 forwarded to the focus item, if any. If the scene loses focus, (i.e.,
96 someone calls clearFocus()) while an item has focus, the scene will
97 maintain its item focus information, and once the scene regains focus, it
98 will make sure the last focus item regains focus.
99
100 For mouse-over effects, QGraphicsScene dispatches \e {hover
101 events}. If an item accepts hover events (see
102 QGraphicsItem::acceptHoverEvents()), it will receive a \l
103 {QEvent::}{GraphicsSceneHoverEnter} event when the mouse enters
104 its area. As the mouse continues moving inside the item's area,
105 QGraphicsScene will send it \l {QEvent::}{GraphicsSceneHoverMove}
106 events. When the mouse leaves the item's area, the item will
107 receive a \l {QEvent::}{GraphicsSceneHoverLeave} event.
108
109 All mouse events are delivered to the current \e {mouse grabber}
110 item. An item becomes the scene's mouse grabber if it accepts
111 mouse events (see QGraphicsItem::acceptedMouseButtons()) and it
112 receives a mouse press. It stays the mouse grabber until it
113 receives a mouse release when no other mouse buttons are
114 pressed. You can call mouseGrabberItem() to determine what item is
115 currently grabbing the mouse.
116
117 \sa QGraphicsItem, QGraphicsView
118*/
119
120/*!
121 \enum QGraphicsScene::SceneLayer
122 \since 4.3
123
124 This enum describes the rendering layers in a QGraphicsScene. When
125 QGraphicsScene draws the scene contents, it renders each of these layers
126 separately, in order.
127
128 Each layer represents a flag that can be OR'ed together when calling
129 functions such as invalidate() or QGraphicsView::invalidateScene().
130
131 \value ItemLayer The item layer. QGraphicsScene renders all items are in
132 this layer by calling the virtual function drawItems(). The item layer is
133 drawn after the background layer, but before the foreground layer.
134
135 \value BackgroundLayer The background layer. QGraphicsScene renders the
136 scene's background in this layer by calling the virtual function
137 drawBackground(). The background layer is drawn first of all layers.
138
139 \value ForegroundLayer The foreground layer. QGraphicsScene renders the
140 scene's foreground in this layer by calling the virtual function
141 drawForeground(). The foreground layer is drawn last of all layers.
142
143 \value AllLayers All layers; this value represents a combination of all
144 three layers.
145
146 \sa invalidate(), QGraphicsView::invalidateScene()
147*/
148
149/*!
150 \enum QGraphicsScene::ItemIndexMethod
151
152 This enum describes the indexing algorithms QGraphicsScene provides for
153 managing positional information about items on the scene.
154
155 \value BspTreeIndex A Binary Space Partitioning tree is applied. All
156 QGraphicsScene's item location algorithms are of an order close to
157 logarithmic complexity, by making use of binary search. Adding, moving and
158 removing items is logarithmic. This approach is best for static scenes
159 (i.e., scenes where most items do not move).
160
161 \value NoIndex No index is applied. Item location is of linear complexity,
162 as all items on the scene are searched. Adding, moving and removing items,
163 however, is done in constant time. This approach is ideal for dynamic
164 scenes, where many items are added, moved or removed continuously.
165
166 \sa setItemIndexMethod(), bspTreeDepth
167*/
168
169#include "qgraphicsscene.h"
170
171#include "qgraphicsitem.h"
172#include "qgraphicsitem_p.h"
173#include "qgraphicslayout.h"
176#include "qgraphicsview.h"
177#include "qgraphicsview_p.h"
178#include "qgraphicswidget.h"
183
184#include <QtCore/qdebug.h>
185#include <QtCore/qlist.h>
186#include <QtCore/qmath.h>
187#include <QtCore/qrect.h>
188#include <QtCore/qset.h>
189#include <QtCore/qstack.h>
190#include <QtCore/qvarlengtharray.h>
191#include <QtCore/QMetaMethod>
192#include <QtWidgets/qapplication.h>
193#include <QtGui/qevent.h>
194#include <QtWidgets/qgesture.h>
195#include <QtWidgets/qgraphicslayout.h>
196#include <QtWidgets/qgraphicsproxywidget.h>
197#include <QtWidgets/qgraphicswidget.h>
198#include <QtGui/qpaintengine.h>
199#include <QtGui/qpainter.h>
200#include <QtGui/qpainterpath.h>
201#include <QtGui/qpixmapcache.h>
202#include <QtGui/qpolygon.h>
203#include <QtGui/qpointingdevice.h>
204#include <QtWidgets/qstyleoption.h>
205#if QT_CONFIG(tooltip)
206#include <QtWidgets/qtooltip.h>
207#endif
208#include <QtGui/qtransform.h>
209#include <QtGui/qinputmethod.h>
210#include <private/qapplication_p.h>
211#include <private/qevent_p.h>
212#include <private/qgesture_p.h>
213#include <QtGui/private/qeventpoint_p.h>
214#include <private/qobject_p.h>
215#if QT_CONFIG(graphicseffect)
216#include <private/qgraphicseffect_p.h>
217#endif
218#include <private/qgesturemanager_p.h>
219#include <private/qpathclipper_p.h>
220
221#include <QtCore/qpointer.h>
222
223// #define GESTURE_DEBUG
224#ifndef GESTURE_DEBUG
225# define DEBUG if (0) qDebug
226#else
227# define DEBUG qDebug
228#endif
229
231
232bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
233
234static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
235{
236 hover->setWidget(mouseEvent->widget());
237 hover->setPos(mouseEvent->pos());
238 hover->setScenePos(mouseEvent->scenePos());
239 hover->setScreenPos(mouseEvent->screenPos());
240 hover->setLastPos(mouseEvent->lastPos());
241 hover->setLastScenePos(mouseEvent->lastScenePos());
242 hover->setLastScreenPos(mouseEvent->lastScreenPos());
243 hover->setModifiers(mouseEvent->modifiers());
244 hover->setAccepted(mouseEvent->isAccepted());
245}
246
247/*!
248 \internal
249*/
250QGraphicsScenePrivate::QGraphicsScenePrivate()
251 : indexMethod(QGraphicsScene::BspTreeIndex),
252 index(nullptr),
253 lastItemCount(0),
254 hasSceneRect(false),
255 dirtyGrowingItemsBoundingRect(true),
256 updateAll(false),
257 calledEmitUpdated(false),
258 processDirtyItemsEmitted(false),
259 needSortTopLevelItems(true),
260 holesInTopLevelSiblingIndex(false),
261 topLevelSequentialOrdering(true),
262 scenePosDescendantsUpdatePending(false),
263 stickyFocus(false),
264 hasFocus(false),
265 lastMouseGrabberItemHasImplicitMouseGrab(false),
266 allItemsIgnoreHoverEvents(true),
267 allItemsUseDefaultCursor(true),
268 painterStateProtection(true),
269 sortCacheEnabled(false),
270 allItemsIgnoreTouchEvents(true),
271 focusOnTouch(true),
272 minimumRenderSize(0.0),
273 selectionChanging(0),
274 rectAdjust(2),
275 focusItem(nullptr),
276 lastFocusItem(nullptr),
277 passiveFocusItem(nullptr),
278 tabFocusFirst(nullptr),
279 activePanel(nullptr),
280 lastActivePanel(nullptr),
281 activationRefCount(0),
282 childExplicitActivation(0),
283 lastMouseGrabberItem(nullptr),
284 dragDropItem(nullptr),
285 enterWidget(nullptr),
286 lastDropAction(Qt::IgnoreAction),
287 style(nullptr)
288{
289}
290
291/*!
292 \internal
293*/
294void QGraphicsScenePrivate::init()
295{
296 Q_Q(QGraphicsScene);
297
298 index = new QGraphicsSceneBspTreeIndex(q);
299
300 // Keep this index so we can check for connected slots later on.
301 changedSignalIndex = signalIndex("changed(QList<QRectF>)");
302 processDirtyItemsIndex = q->metaObject()->indexOfSlot("_q_processDirtyItems()");
303 polishItemsIndex = q->metaObject()->indexOfSlot("_q_polishItems()");
304
305 qApp->d_func()->scene_list.append(q);
306 q->update();
307}
308
309/*!
310 \internal
311*/
312QGraphicsScenePrivate *QGraphicsScenePrivate::get(QGraphicsScene *q)
313{
314 return q->d_func();
315}
316
317void QGraphicsScenePrivate::_q_emitUpdated()
318{
319 Q_Q(QGraphicsScene);
320 calledEmitUpdated = false;
321
322 if (dirtyGrowingItemsBoundingRect) {
323 if (!hasSceneRect) {
324 const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
325 growingItemsBoundingRect |= q->itemsBoundingRect();
326 if (oldGrowingItemsBoundingRect != growingItemsBoundingRect)
327 emit q->sceneRectChanged(growingItemsBoundingRect);
328 }
329 dirtyGrowingItemsBoundingRect = false;
330 }
331
332 // Ensure all views are connected if anything is connected. This disables
333 // the optimization that items send updates directly to the views, but it
334 // needs to happen in order to keep compatibility with the behavior from
335 // Qt 4.4 and backward.
336 if (isSignalConnected(changedSignalIndex)) {
337 for (auto view : std::as_const(views)) {
338 if (!view->d_func()->connectedToScene) {
339 view->d_func()->connectedToScene = true;
340 q->connect(q, SIGNAL(changed(QList<QRectF>)),
341 view, SLOT(updateScene(QList<QRectF>)));
342 }
343 }
344 } else {
345 if (views.isEmpty()) {
346 updateAll = false;
347 return;
348 }
349 for (auto view : std::as_const(views))
350 view->d_func()->processPendingUpdates();
351 // It's important that we update all views before we dispatch, hence two for-loops.
352 for (auto view : std::as_const(views))
353 view->d_func()->dispatchPendingUpdateRequests();
354 return;
355 }
356
357 // Notify the changes to anybody interested.
358 QList<QRectF> oldUpdatedRects;
359 if (updateAll) {
360 oldUpdatedRects << q->sceneRect();
361 } else {
362 // Switch to a ranged constructor in Qt 6...
363 oldUpdatedRects.reserve(int(updatedRects.size()));
364 std::copy(updatedRects.cbegin(), updatedRects.cend(),
365 std::back_inserter(oldUpdatedRects));
366 }
367
368 updateAll = false;
369 updatedRects.clear();
370 emit q->changed(oldUpdatedRects);
371}
372
373/*!
374 \internal
375
376 ### This function is almost identical to QGraphicsItemPrivate::addChild().
377*/
378void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item)
379{
380 ensureSequentialTopLevelSiblingIndexes();
381 needSortTopLevelItems = true; // ### maybe false
382 item->d_ptr->siblingIndex = topLevelItems.size();
383 topLevelItems.append(item);
384}
385
386/*!
387 \internal
388
389 ### This function is almost identical to QGraphicsItemPrivate::removeChild().
390*/
391void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item)
392{
393 if (!holesInTopLevelSiblingIndex)
394 holesInTopLevelSiblingIndex = item->d_ptr->siblingIndex != topLevelItems.size() - 1;
395 if (topLevelSequentialOrdering && !holesInTopLevelSiblingIndex)
396 topLevelItems.removeAt(item->d_ptr->siblingIndex);
397 else
398 topLevelItems.removeOne(item);
399 // NB! Do not use topLevelItems.removeAt(item->d_ptr->siblingIndex) because
400 // the item is not guaranteed to be at the index after the list is sorted
401 // (see ensureSortedTopLevelItems()).
402 item->d_ptr->siblingIndex = -1;
403 if (topLevelSequentialOrdering)
404 topLevelSequentialOrdering = !holesInTopLevelSiblingIndex;
405}
406
407/*!
408 \internal
409*/
410void QGraphicsScenePrivate::_q_polishItems()
411{
412 if (unpolishedItems.isEmpty())
413 return;
414
415 const QVariant booleanTrueVariant(true);
416 QGraphicsItem *item = nullptr;
417 QGraphicsItemPrivate *itemd = nullptr;
418 const int oldUnpolishedCount = unpolishedItems.size();
419
420 for (int i = 0; i < oldUnpolishedCount; ++i) {
421 item = unpolishedItems.at(i);
422 if (!item)
423 continue;
424 itemd = item->d_ptr.data();
425 itemd->pendingPolish = false;
426 if (!itemd->explicitlyHidden) {
427 item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant);
428 item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant);
429 }
430 if (itemd->isWidget) {
431 QEvent event(QEvent::Polish);
432 QCoreApplication::sendEvent((QGraphicsWidget *)item, &event);
433 }
434 }
435
436 if (unpolishedItems.size() == oldUnpolishedCount) {
437 // No new items were added to the vector.
438 unpolishedItems.clear();
439 } else {
440 // New items were appended; keep them and remove the old ones.
441 unpolishedItems.remove(0, oldUnpolishedCount);
442 unpolishedItems.squeeze();
443 QMetaObject::invokeMethod(q_ptr, "_q_polishItems", Qt::QueuedConnection);
444 }
445}
446
447void QGraphicsScenePrivate::_q_processDirtyItems()
448{
449 processDirtyItemsEmitted = false;
450
451 if (updateAll) {
452 Q_ASSERT(calledEmitUpdated);
453 // No need for further processing (except resetting the dirty states).
454 // The growingItemsBoundingRect is updated in _q_emitUpdated.
455 for (auto topLevelItem : std::as_const(topLevelItems))
456 resetDirtyItem(topLevelItem, /*recursive=*/true);
457 return;
458 }
459
460 const bool wasPendingSceneUpdate = calledEmitUpdated;
461 const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect;
462
463 // Process items recursively.
464 for (auto topLevelItem : std::as_const(topLevelItems))
465 processDirtyItemsRecursive(topLevelItem);
466
467 dirtyGrowingItemsBoundingRect = false;
468 if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect)
469 emit q_func()->sceneRectChanged(growingItemsBoundingRect);
470
471 if (wasPendingSceneUpdate)
472 return;
473
474 for (auto view : std::as_const(views))
475 view->d_func()->processPendingUpdates();
476
477 if (calledEmitUpdated) {
478 // We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive
479 // and we cannot wait for the control to reach the eventloop before the
480 // changed signal is emitted, so we emit it now.
481 _q_emitUpdated();
482 }
483
484 // Immediately dispatch all pending update requests on the views.
485 for (auto view : std::as_const(views))
486 view->d_func()->dispatchPendingUpdateRequests();
487}
488
489/*!
490 \internal
491*/
492void QGraphicsScenePrivate::setScenePosItemEnabled(QGraphicsItem *item, bool enabled)
493{
494 QGraphicsItem *p = item->d_ptr->parent;
495 while (p) {
496 p->d_ptr->scenePosDescendants = enabled;
497 p = p->d_ptr->parent;
498 }
499 if (!enabled && !scenePosDescendantsUpdatePending) {
500 scenePosDescendantsUpdatePending = true;
501 QMetaObject::invokeMethod(q_func(), "_q_updateScenePosDescendants", Qt::QueuedConnection);
502 }
503}
504
505/*!
506 \internal
507*/
508void QGraphicsScenePrivate::registerScenePosItem(QGraphicsItem *item)
509{
510 scenePosItems.insert(item);
511 setScenePosItemEnabled(item, true);
512}
513
514/*!
515 \internal
516*/
517void QGraphicsScenePrivate::unregisterScenePosItem(QGraphicsItem *item)
518{
519 scenePosItems.remove(item);
520 setScenePosItemEnabled(item, false);
521}
522
523/*!
524 \internal
525*/
526void QGraphicsScenePrivate::_q_updateScenePosDescendants()
527{
528 for (QGraphicsItem *item : std::as_const(scenePosItems)) {
529 QGraphicsItem *p = item->d_ptr->parent;
530 while (p) {
531 p->d_ptr->scenePosDescendants = 1;
532 p = p->d_ptr->parent;
533 }
534 }
535 scenePosDescendantsUpdatePending = false;
536}
537
538/*!
539 \internal
540
541 Schedules an item for removal. This function leaves some stale indexes
542 around in the BSP tree if called from the item's destructor; these will
543 be cleaned up the next time someone triggers purgeRemovedItems().
544
545 Note: This function might get called from QGraphicsItem's destructor. \a item is
546 being destroyed, so we cannot call any pure virtual functions on it (such
547 as boundingRect()). Also, it is unnecessary to update the item's own state
548 in any way.
549*/
550void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item)
551{
552 Q_Q(QGraphicsScene);
553
554 // Clear focus on the item to remove any reference in the focusWidget chain.
555 item->clearFocus();
556
557 markDirty(item, QRectF(), /*invalidateChildren=*/false, /*force=*/false,
558 /*ignoreOpacity=*/false, /*removingItemFromScene=*/true);
559
560 if (item->d_ptr->inDestructor) {
561 // The item is actually in its destructor, we call the special method in the index.
562 index->deleteItem(item);
563 } else {
564 // Can potentially call item->boundingRect() (virtual function), that's why
565 // we only can call this function if the item is not in its destructor.
566 index->removeItem(item);
567 }
568
569 item->d_ptr->clearSubFocus();
570
571 if (item->flags() & QGraphicsItem::ItemSendsScenePositionChanges)
572 unregisterScenePosItem(item);
573
574 QGraphicsScene *oldScene = item->d_func()->scene;
575 item->d_func()->scene = nullptr;
576
577 //We need to remove all children first because they might use their parent
578 //attributes (e.g. sceneTransform).
579 if (!item->d_ptr->inDestructor) {
580 // Remove all children recursively
581 for (auto child : std::as_const(item->d_ptr->children))
582 q->removeItem(child);
583 }
584
585 if (!item->d_ptr->inDestructor && !item->parentItem() && item->isWidget()) {
586 QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
587 widget->d_func()->fixFocusChainBeforeReparenting(nullptr, oldScene, nullptr);
588 }
589
590 // Unregister focus proxy.
591 item->d_ptr->resetFocusProxy();
592
593 // Remove from parent, or unregister from toplevels.
594 if (QGraphicsItem *parentItem = item->parentItem()) {
595 if (parentItem->scene()) {
596 Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem",
597 "Parent item's scene is different from this item's scene");
598 item->setParentItem(nullptr);
599 }
600 } else {
601 unregisterTopLevelItem(item);
602 }
603
604 // Reset the mouse grabber and focus item data.
605 if (item == focusItem)
606 focusItem = nullptr;
607 if (item == lastFocusItem)
608 lastFocusItem = nullptr;
609 if (item == passiveFocusItem)
610 passiveFocusItem = nullptr;
611 if (item == activePanel) {
612 // ### deactivate...
613 activePanel = nullptr;
614 }
615 if (item == lastActivePanel)
616 lastActivePanel = nullptr;
617
618 // Change tabFocusFirst to the next widget in focus chain if removing the current one.
619 if (item == tabFocusFirst) {
620 QGraphicsWidgetPrivate *wd = tabFocusFirst->d_func();
621 if (wd->focusNext && wd->focusNext != tabFocusFirst && wd->focusNext->scene() == q)
622 tabFocusFirst = wd->focusNext;
623 else
624 tabFocusFirst = nullptr;
625 }
626
627 // Cancel active touches
628 {
629 QMap<int, QGraphicsItem *>::iterator it = itemForTouchPointId.begin();
630 while (it != itemForTouchPointId.end()) {
631 if (it.value() == item) {
632 sceneCurrentTouchPoints.remove(it.key());
633 it = itemForTouchPointId.erase(it);
634 } else {
635 ++it;
636 }
637 }
638 }
639
640 // Disable selectionChanged() for individual items
641 ++selectionChanging;
642 int oldSelectedItemsSize = selectedItems.size();
643
644 // Update selected & hovered item bookkeeping
645 selectedItems.remove(item);
646 hoverItems.removeAll(item);
647 cachedItemsUnderMouse.removeAll(item);
648 if (item->d_ptr->pendingPolish) {
649 const int unpolishedIndex = unpolishedItems.indexOf(item);
650 if (unpolishedIndex != -1)
651 unpolishedItems[unpolishedIndex] = 0;
652 item->d_ptr->pendingPolish = false;
653 }
654 resetDirtyItem(item);
655
656 //We remove all references of item from the sceneEventFilter arrays
657 QMultiMap<QGraphicsItem*, QGraphicsItem*>::iterator iterator = sceneEventFilters.begin();
658 while (iterator != sceneEventFilters.end()) {
659 if (iterator.value() == item || iterator.key() == item)
660 iterator = sceneEventFilters.erase(iterator);
661 else
662 ++iterator;
663 }
664
665 if (item->isPanel() && item->isVisible() && item->panelModality() != QGraphicsItem::NonModal)
666 leaveModal(item);
667
668 // Reset the mouse grabber and focus item data.
669 if (mouseGrabberItems.contains(item))
670 ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor);
671
672 // Reset the keyboard grabber
673 if (keyboardGrabberItems.contains(item))
674 ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor);
675
676 // Reset the last mouse grabber item
677 if (item == lastMouseGrabberItem)
678 lastMouseGrabberItem = nullptr;
679
680 // Reset the current drop item
681 if (item == dragDropItem)
682 dragDropItem = nullptr;
683
684 // Re-enable selectionChanged() for individual items
685 --selectionChanging;
686 if (!selectionChanging && selectedItems.size() != oldSelectedItemsSize)
687 emit q->selectionChanged();
688
689#ifndef QT_NO_GESTURES
690 for (auto it = gestureTargets.begin(); it != gestureTargets.end();) {
691 if (it.value() == item)
692 it = gestureTargets.erase(it);
693 else
694 ++it;
695 }
696
697 if (QGraphicsObject *dummy = item->toGraphicsObject()) {
698 cachedTargetItems.removeOne(dummy);
699 cachedItemGestures.remove(dummy);
700 cachedAlreadyDeliveredGestures.remove(dummy);
701 }
702
703 for (auto it = item->d_ptr->gestureContext.constBegin();
704 it != item->d_ptr->gestureContext.constEnd(); ++it)
705 ungrabGesture(item, it.key());
706#endif // QT_NO_GESTURES
707}
708
709/*!
710 \internal
711*/
712void QGraphicsScenePrivate::setActivePanelHelper(QGraphicsItem *item, bool duringActivationEvent)
713{
714 Q_Q(QGraphicsScene);
715 if (item && item->scene() != q) {
716 qWarning("QGraphicsScene::setActivePanel: item %p must be part of this scene",
717 item);
718 return;
719 }
720
721 // Ensure the scene has focus when we change panel activation.
722 q->setFocus(Qt::ActiveWindowFocusReason);
723
724 // Find the item's panel.
725 QGraphicsItem *panel = item ? item->panel() : nullptr;
726 lastActivePanel = panel ? activePanel : nullptr;
727 if (panel == activePanel || (!q->isActive() && !duringActivationEvent))
728 return;
729
730 QGraphicsItem *oldFocusItem = focusItem;
731
732 // Deactivate the last active panel.
733 if (activePanel) {
734 if (QGraphicsItem *fi = activePanel->focusItem()) {
735 // Remove focus from the current focus item.
736 if (fi == q->focusItem())
737 setFocusItemHelper(nullptr, Qt::ActiveWindowFocusReason, /* emitFocusChanged = */ false);
738 }
739
740 QEvent event(QEvent::WindowDeactivate);
741 q->sendEvent(activePanel, &event);
742 } else if (panel && !duringActivationEvent) {
743 // Deactivate the scene if changing activation to a panel.
744 const auto items = q->items();
745 QEvent event(QEvent::WindowDeactivate);
746 for (QGraphicsItem *item : items) {
747 if (item->isVisible() && !item->isPanel() && !item->parentItem())
748 q->sendEvent(item, &event);
749 }
750 }
751
752 // Update activate state.
753 activePanel = panel;
754 QEvent event(QEvent::ActivationChange);
755 QCoreApplication::sendEvent(q, &event);
756
757 // Activate
758 if (panel) {
759 QEvent event(QEvent::WindowActivate);
760 q->sendEvent(panel, &event);
761
762 // Set focus on the panel's focus item, or itself if it's
763 // focusable, or on the first focusable item in the panel's
764 // focus chain as a last resort.
765 if (QGraphicsItem *focusItem = panel->focusItem()) {
766 setFocusItemHelper(focusItem, Qt::ActiveWindowFocusReason, /* emitFocusChanged = */ false);
767 } else if (panel->flags() & QGraphicsItem::ItemIsFocusable) {
768 setFocusItemHelper(panel, Qt::ActiveWindowFocusReason, /* emitFocusChanged = */ false);
769 } else if (panel->isWidget()) {
770 QGraphicsWidget *fw = static_cast<QGraphicsWidget *>(panel)->d_func()->focusNext;
771 do {
772 if (fw->focusPolicy() & Qt::TabFocus) {
773 setFocusItemHelper(fw, Qt::ActiveWindowFocusReason, /* emitFocusChanged = */ false);
774 break;
775 }
776 fw = fw->d_func()->focusNext;
777 } while (fw != panel);
778 }
779 } else if (q->isActive()) {
780 const auto items = q->items();
781 // Activate the scene
782 QEvent event(QEvent::WindowActivate);
783 for (QGraphicsItem *item : items) {
784 if (item->isVisible() && !item->isPanel() && !item->parentItem())
785 q->sendEvent(item, &event);
786 }
787 }
788
789 emit q->focusItemChanged(focusItem, oldFocusItem, Qt::ActiveWindowFocusReason);
790}
791
792/*!
793 \internal
794
795 \a emitFocusChanged needs to be false when focus passes from one
796 item to another through setActivePanel(); i.e. when activation
797 passes from one panel to another, to avoid getting two focusChanged()
798 emissions; one focusChanged(0, lastFocus), then one
799 focusChanged(newFocus, 0). Instead setActivePanel() emits the signal
800 once itself: focusChanged(newFocus, oldFocus).
801*/
802void QGraphicsScenePrivate::setFocusItemHelper(QGraphicsItem *item,
803 Qt::FocusReason focusReason,
804 bool emitFocusChanged)
805{
806 Q_Q(QGraphicsScene);
807 if (item == focusItem)
808 return;
809
810 // Clear focus if asked to set focus on something that can't
811 // accept input focus.
812 if (item && (!(item->flags() & QGraphicsItem::ItemIsFocusable)
813 || !item->isVisible() || !item->isEnabled())) {
814 item = nullptr;
815 }
816
817 // Set focus on the scene if an item requests focus.
818 if (item) {
819 q->setFocus(focusReason);
820 if (item == focusItem) {
821 if (emitFocusChanged)
822 emit q->focusItemChanged(focusItem, (QGraphicsItem *)nullptr, focusReason);
823 return;
824 }
825 }
826
827 QGraphicsItem *oldFocusItem = focusItem;
828 if (focusItem) {
829 lastFocusItem = focusItem;
830
831#ifndef QT_NO_IM
832 if (lastFocusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod) {
833 // Close any external input method panel. This happens
834 // automatically by removing WA_InputMethodEnabled on
835 // the views, but if we are changing focus, we have to
836 // do it ourselves.
837 if (qApp)
838 QGuiApplication::inputMethod()->commit();
839 }
840#endif //QT_NO_IM
841
842 focusItem = nullptr;
843 QFocusEvent event(QEvent::FocusOut, focusReason);
844 sendEvent(lastFocusItem, &event);
845 }
846
847 // This handles the case that the item has been removed from the
848 // scene in response to the FocusOut event.
849 if (item && item->scene() != q)
850 item = nullptr;
851
852 if (item)
853 focusItem = item;
854 updateInputMethodSensitivityInViews();
855
856 if (item) {
857 QFocusEvent event(QEvent::FocusIn, focusReason);
858 sendEvent(item, &event);
859 }
860
861 if (emitFocusChanged)
862 emit q->focusItemChanged(focusItem, oldFocusItem, focusReason);
863}
864
865/*!
866 \internal
867*/
868void QGraphicsScenePrivate::addPopup(QGraphicsWidget *widget)
869{
870 Q_ASSERT(widget);
871 Q_ASSERT(!popupWidgets.contains(widget));
872 popupWidgets << widget;
873 if (QGraphicsWidget *focusWidget = widget->focusWidget()) {
874 focusWidget->setFocus(Qt::PopupFocusReason);
875 } else {
876 grabKeyboard((QGraphicsItem *)widget);
877 if (focusItem && popupWidgets.size() == 1) {
878 QFocusEvent event(QEvent::FocusOut, Qt::PopupFocusReason);
879 sendEvent(focusItem, &event);
880 }
881 }
882 grabMouse((QGraphicsItem *)widget);
883}
884
885/*!
886 \internal
887
888 Remove \a widget from the popup list. Important notes:
889
890 \a widget is guaranteed to be in the list of popups, but it might not be
891 the last entry; you can hide any item in the pop list before the others,
892 and this must cause all later mouse grabbers to lose the grab.
893*/
894void QGraphicsScenePrivate::removePopup(QGraphicsWidget *widget, bool itemIsDying)
895{
896 Q_ASSERT(widget);
897 int index = popupWidgets.indexOf(widget);
898 Q_ASSERT(index != -1);
899
900 for (int i = popupWidgets.size() - 1; i >= index; --i) {
901 QGraphicsWidget *widget = popupWidgets.takeLast();
902 ungrabMouse(widget, itemIsDying);
903 if (focusItem && popupWidgets.isEmpty()) {
904 QFocusEvent event(QEvent::FocusIn, Qt::PopupFocusReason);
905 sendEvent(focusItem, &event);
906 } else if (keyboardGrabberItems.contains(static_cast<QGraphicsItem *>(widget))) {
907 ungrabKeyboard(static_cast<QGraphicsItem *>(widget), itemIsDying);
908 }
909 if (!itemIsDying && widget->isVisible()) {
910 widget->QGraphicsItem::d_ptr->setVisibleHelper(false, /* explicit = */ false);
911 }
912 }
913}
914
915/*!
916 \internal
917*/
918void QGraphicsScenePrivate::grabMouse(QGraphicsItem *item, bool implicit)
919{
920 // Append to list of mouse grabber items, and send a mouse grab event.
921 if (mouseGrabberItems.contains(item)) {
922 if (mouseGrabberItems.constLast() == item) {
923 Q_ASSERT(!implicit);
924 if (!lastMouseGrabberItemHasImplicitMouseGrab) {
925 qWarning("QGraphicsItem::grabMouse: already a mouse grabber");
926 } else {
927 // Upgrade to an explicit mouse grab
928 lastMouseGrabberItemHasImplicitMouseGrab = false;
929 }
930 } else {
931 qWarning("QGraphicsItem::grabMouse: already blocked by mouse grabber: %p",
932 mouseGrabberItems.constLast());
933 }
934 return;
935 }
936
937 // Send ungrab event to the last grabber.
938 if (!mouseGrabberItems.isEmpty()) {
939 QGraphicsItem *last = mouseGrabberItems.constLast();
940 if (lastMouseGrabberItemHasImplicitMouseGrab) {
941 // Implicit mouse grab is immediately lost.
942 last->ungrabMouse();
943 } else {
944 // Just send ungrab event to current grabber.
945 QEvent ungrabEvent(QEvent::UngrabMouse);
946 sendEvent(last, &ungrabEvent);
947 }
948 }
949
950 mouseGrabberItems << item;
951 lastMouseGrabberItemHasImplicitMouseGrab = implicit;
952
953 // Send grab event to current grabber.
954 QEvent grabEvent(QEvent::GrabMouse);
955 sendEvent(item, &grabEvent);
956}
957
958/*!
959 \internal
960*/
961void QGraphicsScenePrivate::ungrabMouse(QGraphicsItem *item, bool itemIsDying)
962{
963 int index = mouseGrabberItems.indexOf(item);
964 if (index == -1) {
965 qWarning("QGraphicsItem::ungrabMouse: not a mouse grabber");
966 return;
967 }
968
969 if (item != mouseGrabberItems.constLast()) {
970 // Recursively ungrab the next mouse grabber until we reach this item
971 // to ensure state consistency.
972 ungrabMouse(mouseGrabberItems.at(index + 1), itemIsDying);
973 }
974 if (!popupWidgets.isEmpty() && item == popupWidgets.constLast()) {
975 // If the item is a popup, go via removePopup to ensure state
976 // consistency and that it gets hidden correctly - beware that
977 // removePopup() reenters this function to continue removing the grab.
978 removePopup(popupWidgets.constLast(), itemIsDying);
979 return;
980 }
981
982 // Send notification about mouse ungrab.
983 if (!itemIsDying) {
984 QEvent event(QEvent::UngrabMouse);
985 sendEvent(item, &event);
986 }
987
988 // Remove the item from the list of grabbers. Whenever this happens, we
989 // reset the implicitGrab (there can be only ever be one implicit grabber
990 // in a scene, and it is always the latest grabber; if the implicit grab
991 // is lost, it is not automatically regained.
992 mouseGrabberItems.takeLast();
993 lastMouseGrabberItemHasImplicitMouseGrab = false;
994
995 // Send notification about mouse regrab. ### It's unfortunate that all the
996 // items get a GrabMouse event, but this is a rare case with a simple
997 // implementation and it does ensure a consistent state.
998 if (!itemIsDying && !mouseGrabberItems.isEmpty()) {
999 QGraphicsItem *last = mouseGrabberItems.constLast();
1000 QEvent event(QEvent::GrabMouse);
1001 sendEvent(last, &event);
1002 }
1003}
1004
1005/*!
1006 \internal
1007*/
1008void QGraphicsScenePrivate::clearMouseGrabber()
1009{
1010 if (!mouseGrabberItems.isEmpty())
1011 mouseGrabberItems.constFirst()->ungrabMouse();
1012 lastMouseGrabberItem = nullptr;
1013}
1014
1015/*!
1016 \internal
1017*/
1018void QGraphicsScenePrivate::grabKeyboard(QGraphicsItem *item)
1019{
1020 if (keyboardGrabberItems.contains(item)) {
1021 if (keyboardGrabberItems.constLast() == item)
1022 qWarning("QGraphicsItem::grabKeyboard: already a keyboard grabber");
1023 else
1024 qWarning("QGraphicsItem::grabKeyboard: already blocked by keyboard grabber: %p",
1025 keyboardGrabberItems.constLast());
1026 return;
1027 }
1028
1029 // Send ungrab event to the last grabber.
1030 if (!keyboardGrabberItems.isEmpty()) {
1031 // Just send ungrab event to current grabber.
1032 QEvent ungrabEvent(QEvent::UngrabKeyboard);
1033 sendEvent(keyboardGrabberItems.constLast(), &ungrabEvent);
1034 }
1035
1036 keyboardGrabberItems << item;
1037
1038 // Send grab event to current grabber.
1039 QEvent grabEvent(QEvent::GrabKeyboard);
1040 sendEvent(item, &grabEvent);
1041}
1042
1043/*!
1044 \internal
1045*/
1046void QGraphicsScenePrivate::ungrabKeyboard(QGraphicsItem *item, bool itemIsDying)
1047{
1048 int index = keyboardGrabberItems.lastIndexOf(item);
1049 if (index == -1) {
1050 qWarning("QGraphicsItem::ungrabKeyboard: not a keyboard grabber");
1051 return;
1052 }
1053 if (item != keyboardGrabberItems.constLast()) {
1054 // Recursively ungrab the topmost keyboard grabber until we reach this
1055 // item to ensure state consistency.
1056 ungrabKeyboard(keyboardGrabberItems.at(index + 1), itemIsDying);
1057 }
1058
1059 // Send notification about keyboard ungrab.
1060 if (!itemIsDying) {
1061 QEvent event(QEvent::UngrabKeyboard);
1062 sendEvent(item, &event);
1063 }
1064
1065 // Remove the item from the list of grabbers.
1066 keyboardGrabberItems.takeLast();
1067
1068 // Send notification about mouse regrab.
1069 if (!itemIsDying && !keyboardGrabberItems.isEmpty()) {
1070 QGraphicsItem *last = keyboardGrabberItems.constLast();
1071 QEvent event(QEvent::GrabKeyboard);
1072 sendEvent(last, &event);
1073 }
1074}
1075
1076/*!
1077 \internal
1078*/
1079void QGraphicsScenePrivate::clearKeyboardGrabber()
1080{
1081 if (!keyboardGrabberItems.isEmpty())
1082 ungrabKeyboard(keyboardGrabberItems.constFirst());
1083}
1084
1085void QGraphicsScenePrivate::enableMouseTrackingOnViews()
1086{
1087 for (QGraphicsView *view : std::as_const(views))
1088 view->viewport()->setMouseTracking(true);
1089}
1090
1091/*!
1092 \class QGraphicsScenePrivate
1093 \inmodule QtWidgets
1094 \internal
1095*/
1096
1097/*!
1098 Returns all items for the screen position in \a event.
1099*/
1100QList<QGraphicsItem *> QGraphicsScenePrivate::itemsAtPosition(const QPoint &screenPos,
1101 const QPointF &scenePos,
1102 QWidget *widget) const
1103{
1104 Q_Q(const QGraphicsScene);
1105 QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
1106 if (!view)
1107 return q->items(scenePos, Qt::IntersectsItemShape, Qt::DescendingOrder, QTransform());
1108
1109 const QRectF pointRect(QPointF(widget->mapFromGlobal(screenPos)), QSizeF(1, 1));
1110 if (!view->isTransformed())
1111 return q->items(pointRect, Qt::IntersectsItemShape, Qt::DescendingOrder);
1112
1113 const QTransform viewTransform = view->viewportTransform();
1114 if (viewTransform.type() <= QTransform::TxScale) {
1115 return q->items(viewTransform.inverted().mapRect(pointRect), Qt::IntersectsItemShape,
1116 Qt::DescendingOrder, viewTransform);
1117 }
1118 return q->items(viewTransform.inverted().map(pointRect), Qt::IntersectsItemShape,
1119 Qt::DescendingOrder, viewTransform);
1120}
1121
1122/*!
1123 \internal
1124*/
1125void QGraphicsScenePrivate::storeMouseButtonsForMouseGrabber(QGraphicsSceneMouseEvent *event)
1126{
1127 for (int i = 0x1; i <= 0x10; i <<= 1) {
1128 if (event->buttons() & i) {
1129 mouseGrabberButtonDownPos.insert(Qt::MouseButton(i),
1130 mouseGrabberItems.constLast()->d_ptr->genericMapFromScene(event->scenePos(),
1131 event->widget()));
1132 mouseGrabberButtonDownScenePos.insert(Qt::MouseButton(i), event->scenePos());
1133 mouseGrabberButtonDownScreenPos.insert(Qt::MouseButton(i), event->screenPos());
1134 }
1135 }
1136}
1137
1138/*!
1139 \internal
1140*/
1141void QGraphicsScenePrivate::installSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
1142{
1143 sceneEventFilters.insert(watched, filter);
1144}
1145
1146/*!
1147 \internal
1148*/
1149void QGraphicsScenePrivate::removeSceneEventFilter(QGraphicsItem *watched, QGraphicsItem *filter)
1150{
1151 if (!sceneEventFilters.contains(watched))
1152 return;
1153
1154 QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(watched);
1155 QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(watched);
1156 do {
1157 if (it.value() == filter)
1158 it = sceneEventFilters.erase(it);
1159 else
1160 ++it;
1161 } while (it != end);
1162}
1163
1164/*!
1165 \internal
1166*/
1167bool QGraphicsScenePrivate::filterDescendantEvent(QGraphicsItem *item, QEvent *event)
1168{
1169 if (item && (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorFiltersChildEvents)) {
1170 QGraphicsItem *parent = item->parentItem();
1171 while (parent) {
1172 if (parent->d_ptr->filtersDescendantEvents && parent->sceneEventFilter(item, event))
1173 return true;
1174 if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorFiltersChildEvents))
1175 return false;
1176 parent = parent->parentItem();
1177 }
1178 }
1179 return false;
1180}
1181
1182/*!
1183 \internal
1184*/
1185bool QGraphicsScenePrivate::filterEvent(QGraphicsItem *item, QEvent *event)
1186{
1187 if (item && !sceneEventFilters.contains(item))
1188 return false;
1189
1190 QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator it = sceneEventFilters.lowerBound(item);
1191 QMultiMap<QGraphicsItem *, QGraphicsItem *>::Iterator end = sceneEventFilters.upperBound(item);
1192 while (it != end) {
1193 // ### The filterer and filteree might both be deleted.
1194 if (it.value()->sceneEventFilter(it.key(), event))
1195 return true;
1196 ++it;
1197 }
1198 return false;
1199}
1200
1201/*!
1202 \internal
1203
1204 This is the final dispatch point for any events from the scene to the
1205 item. It filters the event first - if the filter returns \c true, the event
1206 is considered to have been eaten by the filter, and is therefore stopped
1207 (the default filter returns \c false). Then/otherwise, if the item is
1208 enabled, the event is sent; otherwise it is stopped.
1209*/
1210bool QGraphicsScenePrivate::sendEvent(QGraphicsItem *item, QEvent *event)
1211{
1212#if QT_CONFIG(gestures)
1213 if (QGraphicsObject *object = item->toGraphicsObject()) {
1214 QGestureManager *gestureManager = QApplicationPrivate::instance()->gestureManager;
1215 if (gestureManager) {
1216 if (gestureManager->filterEvent(object, event))
1217 return true;
1218 }
1219 }
1220#endif // QT_CONFIG(gestures)
1221
1222 if (filterEvent(item, event))
1223 return false;
1224 if (filterDescendantEvent(item, event))
1225 return false;
1226 if (!item || !item->isEnabled())
1227 return false;
1228 if (QGraphicsObject *o = item->toGraphicsObject()) {
1229 bool spont = event->spontaneous();
1230 if (spont ? qt_sendSpontaneousEvent(o, event) : QCoreApplication::sendEvent(o, event))
1231 return true;
1232 event->m_spont = spont;
1233 }
1234 return item->sceneEvent(event);
1235}
1236
1237/*!
1238 \internal
1239*/
1240void QGraphicsScenePrivate::cloneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
1241 QGraphicsSceneDragDropEvent *source)
1242{
1243 dest->setWidget(source->widget());
1244 dest->setPos(source->pos());
1245 dest->setScenePos(source->scenePos());
1246 dest->setScreenPos(source->screenPos());
1247 dest->setButtons(source->buttons());
1248 dest->setModifiers(source->modifiers());
1249 dest->setPossibleActions(source->possibleActions());
1250 dest->setProposedAction(source->proposedAction());
1251 dest->setDropAction(source->dropAction());
1252 dest->setSource(source->source());
1253 dest->setMimeData(source->mimeData());
1254}
1255
1256/*!
1257 \internal
1258*/
1259void QGraphicsScenePrivate::sendDragDropEvent(QGraphicsItem *item,
1260 QGraphicsSceneDragDropEvent *dragDropEvent)
1261{
1262 dragDropEvent->setPos(item->d_ptr->genericMapFromScene(dragDropEvent->scenePos(), dragDropEvent->widget()));
1263 sendEvent(item, dragDropEvent);
1264}
1265
1266/*!
1267 \internal
1268*/
1269void QGraphicsScenePrivate::sendHoverEvent(QEvent::Type type, QGraphicsItem *item,
1270 QGraphicsSceneHoverEvent *hoverEvent)
1271{
1272 QGraphicsSceneHoverEvent event(type);
1273 event.setWidget(hoverEvent->widget());
1274 const QTransform mapFromScene = item->d_ptr->genericMapFromSceneTransform(hoverEvent->widget());
1275 event.setPos(mapFromScene.map(hoverEvent->scenePos()));
1276 event.setScenePos(hoverEvent->scenePos());
1277 event.setScreenPos(hoverEvent->screenPos());
1278 event.setLastPos(mapFromScene.map(hoverEvent->lastScenePos()));
1279 event.setLastScenePos(hoverEvent->lastScenePos());
1280 event.setLastScreenPos(hoverEvent->lastScreenPos());
1281 event.setModifiers(hoverEvent->modifiers());
1282 sendEvent(item, &event);
1283}
1284
1285/*!
1286 \internal
1287*/
1288void QGraphicsScenePrivate::sendMouseEvent(QGraphicsSceneMouseEvent *mouseEvent)
1289{
1290 if (mouseEvent->button() == 0 && mouseEvent->buttons() == 0 && lastMouseGrabberItemHasImplicitMouseGrab) {
1291 // ### This is a temporary fix for until we get proper mouse
1292 // grab events.
1293 clearMouseGrabber();
1294 return;
1295 }
1296
1297 QGraphicsItem *item = mouseGrabberItems.constLast();
1298 if (item->isBlockedByModalPanel())
1299 return;
1300
1301 const QTransform mapFromScene = item->d_ptr->genericMapFromSceneTransform(mouseEvent->widget());
1302 const QPointF itemPos = mapFromScene.map(mouseEvent->scenePos());
1303 for (int i = 0x1; i <= 0x10; i <<= 1) {
1304 Qt::MouseButton button = Qt::MouseButton(i);
1305 mouseEvent->setButtonDownPos(button, mouseGrabberButtonDownPos.value(button, itemPos));
1306 mouseEvent->setButtonDownScenePos(button, mouseGrabberButtonDownScenePos.value(button, mouseEvent->scenePos()));
1307 mouseEvent->setButtonDownScreenPos(button, mouseGrabberButtonDownScreenPos.value(button, mouseEvent->screenPos()));
1308 }
1309 mouseEvent->setPos(itemPos);
1310 mouseEvent->setLastPos(mapFromScene.map(mouseEvent->lastScenePos()));
1311 sendEvent(item, mouseEvent);
1312}
1313
1314/*!
1315 \internal
1316*/
1317void QGraphicsScenePrivate::mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent)
1318{
1319 Q_Q(QGraphicsScene);
1320
1321 // Ignore by default, unless we find a mouse grabber that accepts it.
1322 mouseEvent->ignore();
1323
1324 // Deliver to any existing mouse grabber.
1325 if (!mouseGrabberItems.isEmpty()) {
1326 if (mouseGrabberItems.constLast()->isBlockedByModalPanel())
1327 return;
1328 // The event is ignored by default, but we disregard the event's
1329 // accepted state after delivery; the mouse is grabbed, after all.
1330 sendMouseEvent(mouseEvent);
1331 return;
1332 }
1333
1334 // Start by determining the number of items at the current position.
1335 // Reuse value from earlier calculations if possible.
1336 if (cachedItemsUnderMouse.isEmpty()) {
1337 cachedItemsUnderMouse = itemsAtPosition(mouseEvent->screenPos(),
1338 mouseEvent->scenePos(),
1339 mouseEvent->widget());
1340 }
1341
1342 // Update window activation.
1343 QGraphicsItem *topItem = cachedItemsUnderMouse.value(0);
1344 QGraphicsWidget *newActiveWindow = topItem ? topItem->window() : nullptr;
1345 if (newActiveWindow && newActiveWindow->isBlockedByModalPanel(&topItem)) {
1346 // pass activation to the blocking modal window
1347 newActiveWindow = topItem ? topItem->window() : nullptr;
1348 }
1349
1350 if (newActiveWindow != q->activeWindow())
1351 q->setActiveWindow(newActiveWindow);
1352
1353 // Set focus on the topmost enabled item that can take focus.
1354 bool setFocus = false;
1355
1356 for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
1357 if (item->isBlockedByModalPanel()
1358 || (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling)) {
1359 // Make sure we don't clear focus.
1360 setFocus = true;
1361 break;
1362 }
1363 if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable))) {
1364 if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
1365 setFocus = true;
1366 if (item != q->focusItem() && item->d_ptr->mouseSetsFocus)
1367 q->setFocusItem(item, Qt::MouseFocusReason);
1368 break;
1369 }
1370 }
1371 if (item->isPanel())
1372 break;
1373 if (item->d_ptr->flags & QGraphicsItem::ItemStopsClickFocusPropagation)
1374 break;
1375 }
1376
1377 // Check for scene modality.
1378 bool sceneModality = false;
1379 for (auto modalPanel : std::as_const(modalPanels)) {
1380 if (modalPanel->panelModality() == QGraphicsItem::SceneModal) {
1381 sceneModality = true;
1382 break;
1383 }
1384 }
1385
1386 // If nobody could take focus, clear it.
1387 if (!stickyFocus && !setFocus && !sceneModality)
1388 q->setFocusItem(nullptr, Qt::MouseFocusReason);
1389
1390 // Any item will do.
1391 if (sceneModality && cachedItemsUnderMouse.isEmpty())
1392 cachedItemsUnderMouse << modalPanels.constFirst();
1393
1394 // Find a mouse grabber by sending mouse press events to all mouse grabber
1395 // candidates one at a time, until the event is accepted. It's accepted by
1396 // default, so the receiver has to explicitly ignore it for it to pass
1397 // through.
1398 for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
1399 if (!(item->acceptedMouseButtons() & mouseEvent->button())) {
1400 // Skip items that don't accept the event's mouse button.
1401 continue;
1402 }
1403
1404 // Check if this item is blocked by a modal panel and deliver the mouse event to the
1405 // blocking panel instead of this item if blocked.
1406 (void) item->isBlockedByModalPanel(&item);
1407
1408 grabMouse(item, /* implicit = */ true);
1409 mouseEvent->accept();
1410
1411 // check if the item we are sending to are disabled (before we send the event)
1412 bool disabled = !item->isEnabled();
1413 bool isPanel = item->isPanel();
1414 if (mouseEvent->type() == QEvent::GraphicsSceneMouseDoubleClick
1415 && item != lastMouseGrabberItem && lastMouseGrabberItem) {
1416 // If this item is different from the item that received the last
1417 // mouse event, and mouseEvent is a double-click event, then the
1418 // event is converted to a press. Known limitation:
1419 // Triple-clicking will not generate a double-click, though.
1420 QGraphicsSceneMouseEvent mousePress(QEvent::GraphicsSceneMousePress);
1421 mousePress.m_spont = mouseEvent->spontaneous();
1422 mousePress.accept();
1423 mousePress.setButton(mouseEvent->button());
1424 mousePress.setButtons(mouseEvent->buttons());
1425 mousePress.setScreenPos(mouseEvent->screenPos());
1426 mousePress.setScenePos(mouseEvent->scenePos());
1427 mousePress.setModifiers(mouseEvent->modifiers());
1428 mousePress.setWidget(mouseEvent->widget());
1429 mousePress.setButtonDownPos(mouseEvent->button(),
1430 mouseEvent->buttonDownPos(mouseEvent->button()));
1431 mousePress.setButtonDownScenePos(mouseEvent->button(),
1432 mouseEvent->buttonDownScenePos(mouseEvent->button()));
1433 mousePress.setButtonDownScreenPos(mouseEvent->button(),
1434 mouseEvent->buttonDownScreenPos(mouseEvent->button()));
1435 sendMouseEvent(&mousePress);
1436 mouseEvent->setAccepted(mousePress.isAccepted());
1437 } else {
1438 sendMouseEvent(mouseEvent);
1439 }
1440
1441 bool dontSendUngrabEvents = mouseGrabberItems.isEmpty() || mouseGrabberItems.constLast() != item;
1442 if (disabled) {
1443 ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
1444 break;
1445 }
1446 if (mouseEvent->isAccepted()) {
1447 if (!mouseGrabberItems.isEmpty())
1448 storeMouseButtonsForMouseGrabber(mouseEvent);
1449 lastMouseGrabberItem = item;
1450 return;
1451 }
1452 ungrabMouse(item, /* itemIsDying = */ dontSendUngrabEvents);
1453
1454 // Don't propagate through panels.
1455 if (isPanel)
1456 break;
1457 }
1458
1459 // Is the event still ignored? Then the mouse press goes to the scene.
1460 // Reset the mouse grabber, clear the selection, clear focus, and leave
1461 // the event ignored so that it can propagate through the originating
1462 // view.
1463 if (!mouseEvent->isAccepted()) {
1464 clearMouseGrabber();
1465
1466 QGraphicsView *view = mouseEvent->widget() ? qobject_cast<QGraphicsView *>(mouseEvent->widget()->parentWidget()) : 0;
1467 bool dontClearSelection = view && view->dragMode() == QGraphicsView::ScrollHandDrag;
1468 bool extendSelection = (mouseEvent->modifiers() & Qt::ControlModifier) != 0;
1469 dontClearSelection |= extendSelection;
1470 if (!dontClearSelection) {
1471 // Clear the selection if the originating view isn't in scroll
1472 // hand drag mode. The view will clear the selection if no drag
1473 // happened.
1474 q->clearSelection();
1475 }
1476 }
1477}
1478
1479/*!
1480 \internal
1481
1482 Ensures that the list of toplevels is sorted by insertion order, and that
1483 the siblingIndexes are packed (no gaps), and start at 0.
1484
1485 ### This function is almost identical to
1486 QGraphicsItemPrivate::ensureSequentialSiblingIndex().
1487*/
1488void QGraphicsScenePrivate::ensureSequentialTopLevelSiblingIndexes()
1489{
1490 if (!topLevelSequentialOrdering) {
1491 std::sort(topLevelItems.begin(), topLevelItems.end(), QGraphicsItemPrivate::insertionOrder);
1492 topLevelSequentialOrdering = true;
1493 needSortTopLevelItems = 1;
1494 }
1495 if (holesInTopLevelSiblingIndex) {
1496 holesInTopLevelSiblingIndex = 0;
1497 for (int i = 0; i < topLevelItems.size(); ++i)
1498 topLevelItems[i]->d_ptr->siblingIndex = i;
1499 }
1500}
1501
1502/*!
1503 \internal
1504
1505 Set the font and propagate the changes if the font is different from the
1506 current font.
1507*/
1508void QGraphicsScenePrivate::setFont_helper(const QFont &font)
1509{
1510 if (this->font == font && this->font.resolveMask() == font.resolveMask())
1511 return;
1512 updateFont(font);
1513}
1514
1515/*!
1516 \internal
1517
1518 Resolve the scene's font against the application font, and propagate the
1519 changes too all items in the scene.
1520*/
1521void QGraphicsScenePrivate::resolveFont()
1522{
1523 QFont naturalFont = QApplication::font();
1524 naturalFont.setResolveMask(0);
1525 QFont resolvedFont = font.resolve(naturalFont);
1526 updateFont(resolvedFont);
1527}
1528
1529/*!
1530 \internal
1531
1532 Update the font, and whether or not it has changed, reresolve all fonts in
1533 the scene.
1534*/
1535void QGraphicsScenePrivate::updateFont(const QFont &font)
1536{
1537 Q_Q(QGraphicsScene);
1538
1539 // Update local font setting.
1540 this->font = font;
1541
1542 // Resolve the fonts of all top-level widget items, or widget items
1543 // whose parent is not a widget.
1544 const auto items = q->items();
1545 for (QGraphicsItem *item : items) {
1546 if (!item->parentItem()) {
1547 // Resolvefont for an item is a noop operation, but
1548 // every item can be a widget, or can have a widget
1549 // childre.
1550 item->d_ptr->resolveFont(font.resolveMask());
1551 }
1552 }
1553
1554 // Send the scene a FontChange event.
1555 QEvent event(QEvent::FontChange);
1556 QCoreApplication::sendEvent(q, &event);
1557}
1558
1559/*!
1560 \internal
1561
1562 Set the palette and propagate the changes if the palette is different from
1563 the current palette.
1564*/
1565void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette)
1566{
1567 if (this->palette == palette && this->palette.resolveMask() == palette.resolveMask())
1568 return;
1569 updatePalette(palette);
1570}
1571
1572/*!
1573 \internal
1574
1575 Resolve the scene's palette against the application palette, and propagate
1576 the changes too all items in the scene.
1577*/
1578void QGraphicsScenePrivate::resolvePalette()
1579{
1580 QPalette naturalPalette = QGuiApplication::palette();
1581 naturalPalette.setResolveMask(0);
1582 QPalette resolvedPalette = palette.resolve(naturalPalette);
1583 updatePalette(resolvedPalette);
1584}
1585
1586/*!
1587 \internal
1588
1589 Update the palette, and whether or not it has changed, reresolve all
1590 palettes in the scene.
1591*/
1592void QGraphicsScenePrivate::updatePalette(const QPalette &palette)
1593{
1594 Q_Q(QGraphicsScene);
1595
1596 // Update local palette setting.
1597 this->palette = palette;
1598
1599 // Resolve the palettes of all top-level widget items, or widget items
1600 // whose parent is not a widget.
1601 const auto items = q->items();
1602 for (QGraphicsItem *item : items) {
1603 if (!item->parentItem()) {
1604 // ResolvePalette for an item is a noop operation, but
1605 // every item can be a widget, or can have a widget
1606 // children.
1607 item->d_ptr->resolvePalette(palette.resolveMask());
1608 }
1609 }
1610
1611 // Send the scene a PaletteChange event.
1612 QEvent event(QEvent::PaletteChange);
1613 QCoreApplication::sendEvent(q, &event);
1614}
1615
1616/*!
1617 Constructs a QGraphicsScene object. The \a parent parameter is
1618 passed to QObject's constructor.
1619*/
1620QGraphicsScene::QGraphicsScene(QObject *parent)
1621 : QObject(*new QGraphicsScenePrivate, parent)
1622{
1623 d_func()->init();
1624}
1625
1626/*!
1627 Constructs a QGraphicsScene object, using \a sceneRect for its
1628 scene rectangle. The \a parent parameter is passed to QObject's
1629 constructor.
1630
1631 \sa sceneRect
1632*/
1633QGraphicsScene::QGraphicsScene(const QRectF &sceneRect, QObject *parent)
1634 : QObject(*new QGraphicsScenePrivate, parent)
1635{
1636 d_func()->init();
1637 setSceneRect(sceneRect);
1638}
1639
1640/*!
1641 Constructs a QGraphicsScene object, using the rectangle specified
1642 by (\a x, \a y), and the given \a width and \a height for its
1643 scene rectangle. The \a parent parameter is passed to QObject's
1644 constructor.
1645
1646 \sa sceneRect
1647*/
1648QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject *parent)
1649 : QObject(*new QGraphicsScenePrivate, parent)
1650{
1651 d_func()->init();
1652 setSceneRect(x, y, width, height);
1653}
1654
1655/*!
1656 Removes and deletes all items from the scene object
1657 before destroying the scene object. The scene object
1658 is removed from the application's global scene list,
1659 and it is removed from all associated views.
1660*/
1661QGraphicsScene::~QGraphicsScene()
1662{
1663 Q_D(QGraphicsScene);
1664
1665 // Remove this scene from qApp's global scene list.
1666 if (!QApplicationPrivate::is_app_closing)
1667 qApp->d_func()->scene_list.removeAll(this);
1668
1669 clear();
1670
1671 // Remove this scene from all associated views.
1672 // Note: d->views is modified by QGraphicsView::setScene, so must make a copy
1673 const auto views = d->views;
1674 for (auto view : std::as_const(views))
1675 view->setScene(nullptr);
1676}
1677
1678/*!
1679 \property QGraphicsScene::sceneRect
1680 \brief the scene rectangle; the bounding rectangle of the scene
1681
1682 The scene rectangle defines the extent of the scene. It is
1683 primarily used by QGraphicsView to determine the view's default
1684 scrollable area, and by QGraphicsScene to manage item indexing.
1685
1686 If unset, or if set to a null QRectF, sceneRect() will return the largest
1687 bounding rect of all items on the scene since the scene was created (i.e.,
1688 a rectangle that grows when items are added to or moved in the scene, but
1689 never shrinks).
1690
1691 \sa width(), height(), QGraphicsView::sceneRect
1692*/
1693QRectF QGraphicsScene::sceneRect() const
1694{
1695 Q_D(const QGraphicsScene);
1696 if (d->hasSceneRect)
1697 return d->sceneRect;
1698
1699 if (d->dirtyGrowingItemsBoundingRect) {
1700 // Lazily update the growing items bounding rect
1701 QGraphicsScenePrivate *thatd = const_cast<QGraphicsScenePrivate *>(d);
1702 QRectF oldGrowingBoundingRect = thatd->growingItemsBoundingRect;
1703 thatd->growingItemsBoundingRect |= itemsBoundingRect();
1704 thatd->dirtyGrowingItemsBoundingRect = false;
1705 if (oldGrowingBoundingRect != thatd->growingItemsBoundingRect)
1706 emit const_cast<QGraphicsScene *>(this)->sceneRectChanged(thatd->growingItemsBoundingRect);
1707 }
1708 return d->growingItemsBoundingRect;
1709}
1710void QGraphicsScene::setSceneRect(const QRectF &rect)
1711{
1712 Q_D(QGraphicsScene);
1713 if (rect != d->sceneRect) {
1714 d->hasSceneRect = !rect.isNull();
1715 d->sceneRect = rect;
1716 emit sceneRectChanged(d->hasSceneRect ? rect : d->growingItemsBoundingRect);
1717 }
1718}
1719
1720/*!
1721 \fn qreal QGraphicsScene::width() const
1722
1723 This convenience function is equivalent to calling sceneRect().width().
1724
1725 \sa height()
1726*/
1727
1728/*!
1729 \fn qreal QGraphicsScene::height() const
1730
1731 This convenience function is equivalent to calling \c sceneRect().height().
1732
1733 \sa width()
1734*/
1735
1736/*!
1737 Renders the \a source rect from scene into \a target, using \a painter. This
1738 function is useful for capturing the contents of the scene onto a paint
1739 device, such as a QImage (e.g., to take a screenshot), or for printing
1740 with QPrinter. For example:
1741
1742 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 1
1743
1744 If \a source is a null rect, this function will use sceneRect() to
1745 determine what to render. If \a target is a null rect, the dimensions of \a
1746 painter's paint device will be used.
1747
1748 The source rect contents will be transformed according to \a
1749 aspectRatioMode to fit into the target rect. By default, the aspect ratio
1750 is kept, and \a source is scaled to fit in \a target.
1751
1752 \sa QGraphicsView::render()
1753*/
1754void QGraphicsScene::render(QPainter *painter, const QRectF &target, const QRectF &source,
1755 Qt::AspectRatioMode aspectRatioMode)
1756{
1757 // ### Switch to using the recursive rendering algorithm instead.
1758
1759 // Default source rect = scene rect
1760 QRectF sourceRect = source;
1761 if (sourceRect.isNull())
1762 sourceRect = sceneRect();
1763
1764 // Default target rect = device rect
1765 QRectF targetRect = target;
1766 if (targetRect.isNull()) {
1767 if (painter->device()->devType() == QInternal::Picture)
1768 targetRect = sourceRect;
1769 else
1770 targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
1771 }
1772
1773 // Find the ideal x / y scaling ratio to fit \a source into \a target.
1774 qreal xratio = targetRect.width() / sourceRect.width();
1775 qreal yratio = targetRect.height() / sourceRect.height();
1776
1777 // Scale according to the aspect ratio mode.
1778 switch (aspectRatioMode) {
1779 case Qt::KeepAspectRatio:
1780 xratio = yratio = qMin(xratio, yratio);
1781 break;
1782 case Qt::KeepAspectRatioByExpanding:
1783 xratio = yratio = qMax(xratio, yratio);
1784 break;
1785 case Qt::IgnoreAspectRatio:
1786 break;
1787 }
1788
1789 // Find all items to draw, and reverse the list (we want to draw
1790 // in reverse order).
1791 QList<QGraphicsItem *> itemList = items(sourceRect, Qt::IntersectsItemBoundingRect);
1792 QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
1793 const qsizetype numItems = itemList.size();
1794 for (qsizetype i = 0; i < numItems; ++i)
1795 itemArray[numItems - i - 1] = itemList.at(i);
1796 itemList.clear();
1797
1798 painter->save();
1799
1800 // Transform the painter.
1801 painter->setClipRect(targetRect, Qt::IntersectClip);
1802 QTransform painterTransform;
1803 painterTransform *= QTransform()
1804 .translate(targetRect.left(), targetRect.top())
1805 .scale(xratio, yratio)
1806 .translate(-sourceRect.left(), -sourceRect.top());
1807 painter->setWorldTransform(painterTransform, true);
1808
1809 // Generate the style options
1810 QStyleOptionGraphicsItem *styleOptionArray = new QStyleOptionGraphicsItem[numItems];
1811 for (qsizetype i = 0; i < numItems; ++i)
1812 itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterTransform, targetRect.toRect());
1813
1814 // Render the scene.
1815 drawBackground(painter, sourceRect);
1816 drawItems(painter, numItems, itemArray, styleOptionArray);
1817 drawForeground(painter, sourceRect);
1818
1819 delete [] itemArray;
1820 delete [] styleOptionArray;
1821
1822 painter->restore();
1823}
1824
1825/*!
1826 \property QGraphicsScene::itemIndexMethod
1827 \brief the item indexing method.
1828
1829 QGraphicsScene applies an indexing algorithm to the scene, to speed up
1830 item discovery functions like items() and itemAt(). Indexing is most
1831 efficient for static scenes (i.e., where items don't move around). For
1832 dynamic scenes, or scenes with many animated items, the index bookkeeping
1833 can outweigh the fast lookup speeds.
1834
1835 For the common case, the default index method BspTreeIndex works fine. If
1836 your scene uses many animations and you are experiencing slowness, you can
1837 disable indexing by calling \c setItemIndexMethod(NoIndex).
1838
1839 \sa bspTreeDepth
1840*/
1841QGraphicsScene::ItemIndexMethod QGraphicsScene::itemIndexMethod() const
1842{
1843 Q_D(const QGraphicsScene);
1844 return d->indexMethod;
1845}
1846void QGraphicsScene::setItemIndexMethod(ItemIndexMethod method)
1847{
1848 Q_D(QGraphicsScene);
1849 if (d->indexMethod == method)
1850 return;
1851
1852 d->indexMethod = method;
1853
1854 QList<QGraphicsItem *> oldItems = d->index->items(Qt::DescendingOrder);
1855 delete d->index;
1856 if (method == BspTreeIndex)
1857 d->index = new QGraphicsSceneBspTreeIndex(this);
1858 else
1859 d->index = new QGraphicsSceneLinearIndex(this);
1860 for (int i = oldItems.size() - 1; i >= 0; --i)
1861 d->index->addItem(oldItems.at(i));
1862}
1863
1864/*!
1865 \property QGraphicsScene::bspTreeDepth
1866 \brief the depth of QGraphicsScene's BSP index tree
1867 \since 4.3
1868
1869 This property has no effect when NoIndex is used.
1870
1871 This value determines the depth of QGraphicsScene's BSP tree. The depth
1872 directly affects QGraphicsScene's performance and memory usage; the latter
1873 growing exponentially with the depth of the tree. With an optimal tree
1874 depth, QGraphicsScene can instantly determine the locality of items, even
1875 for scenes with thousands or millions of items. This also greatly improves
1876 rendering performance.
1877
1878 By default, the value is 0, in which case Qt will guess a reasonable
1879 default depth based on the size, location and number of items in the
1880 scene. If these parameters change frequently, however, you may experience
1881 slowdowns as QGraphicsScene retunes the depth internally. You can avoid
1882 potential slowdowns by fixating the tree depth through setting this
1883 property.
1884
1885 The depth of the tree and the size of the scene rectangle decide the
1886 granularity of the scene's partitioning. The size of each scene segment is
1887 determined by the following algorithm:
1888
1889 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 2
1890
1891 The BSP tree has an optimal size when each segment contains between 0 and
1892 10 items.
1893
1894 \sa itemIndexMethod
1895*/
1896int QGraphicsScene::bspTreeDepth() const
1897{
1898 Q_D(const QGraphicsScene);
1899 QGraphicsSceneBspTreeIndex *bspTree = qobject_cast<QGraphicsSceneBspTreeIndex *>(d->index);
1900 return bspTree ? bspTree->bspTreeDepth() : 0;
1901}
1902void QGraphicsScene::setBspTreeDepth(int depth)
1903{
1904 Q_D(QGraphicsScene);
1905 if (depth < 0) {
1906 qWarning("QGraphicsScene::setBspTreeDepth: invalid depth %d ignored; must be >= 0", depth);
1907 return;
1908 }
1909
1910 QGraphicsSceneBspTreeIndex *bspTree = qobject_cast<QGraphicsSceneBspTreeIndex *>(d->index);
1911 if (!bspTree) {
1912 qWarning("QGraphicsScene::setBspTreeDepth: cannot apply if indexing method is not BSP");
1913 return;
1914 }
1915 bspTree->setBspTreeDepth(depth);
1916}
1917
1918/*!
1919 Calculates and returns the bounding rect of all items on the scene. This
1920 function works by iterating over all items, and because of this, it can
1921 be slow for large scenes.
1922
1923 \sa sceneRect()
1924*/
1925QRectF QGraphicsScene::itemsBoundingRect() const
1926{
1927 // Does not take untransformable items into account.
1928 QRectF boundingRect;
1929 const auto items_ = items();
1930 for (QGraphicsItem *item : items_)
1931 boundingRect |= item->sceneBoundingRect();
1932 return boundingRect;
1933}
1934
1935/*!
1936 Returns an ordered list of all items on the scene. \a order decides the
1937 stacking order.
1938
1939 \sa addItem(), removeItem(), {QGraphicsItem#Sorting}{Sorting}
1940*/
1941QList<QGraphicsItem *> QGraphicsScene::items(Qt::SortOrder order) const
1942{
1943 Q_D(const QGraphicsScene);
1944 return d->index->items(order);
1945}
1946
1947/*!
1948 \fn QList<QGraphicsItem *> QGraphicsScene::items(qreal x, qreal y, qreal w, qreal h, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
1949 \overload
1950 \since 4.6
1951
1952 \brief Returns all visible items that, depending on \a mode, are
1953 either inside or intersect with the rectangle defined by \a x, \a y,
1954 \a w and \a h, in a list sorted using \a order. In this case, "visible" defines items for which:
1955 isVisible() returns \c true, effectiveOpacity() returns a value greater than 0.0
1956 (which is fully transparent) and the parent item does not clip it.
1957
1958 \a deviceTransform is the transformation that applies to the view, and needs to
1959 be provided if the scene contains items that ignore transformations.
1960*/
1961
1962/*!
1963 \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
1964 \since 4.6
1965
1966 \brief Returns all visible items that, depending on \a mode, are at
1967 the specified \a pos in a list sorted using \a order. In this case, "visible" defines items for which:
1968 isVisible() returns \c true, effectiveOpacity() returns a value greater than 0.0
1969 (which is fully transparent) and the parent item does not clip it.
1970
1971 The default value for \a mode is Qt::IntersectsItemShape; all items whose
1972 exact shape intersects with \a pos are returned.
1973
1974 \a deviceTransform is the transformation that applies to the view, and needs to
1975 be provided if the scene contains items that ignore transformations.
1976
1977 \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
1978*/
1979QList<QGraphicsItem *> QGraphicsScene::items(const QPointF &pos, Qt::ItemSelectionMode mode,
1980 Qt::SortOrder order, const QTransform &deviceTransform) const
1981{
1982 Q_D(const QGraphicsScene);
1983 return d->index->items(pos, mode, order, deviceTransform);
1984}
1985
1986/*!
1987 \fn QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
1988 \overload
1989 \since 4.6
1990
1991 \brief Returns all visible items that, depending on \a mode, are
1992 either inside or intersect with the specified \a rect, in a
1993 list sorted using \a order. In this case, "visible" defines items for which:
1994 isVisible() returns \c true, effectiveOpacity() returns a value greater than 0.0
1995 (which is fully transparent) and the parent item does not clip it.
1996
1997 The default value for \a mode is Qt::IntersectsItemShape; all items whose
1998 exact shape intersects with or is contained by \a rect are returned.
1999
2000 \a deviceTransform is the transformation that applies to the view, and needs to
2001 be provided if the scene contains items that ignore transformations.
2002
2003 \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
2004*/
2005QList<QGraphicsItem *> QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode,
2006 Qt::SortOrder order, const QTransform &deviceTransform) const
2007{
2008 Q_D(const QGraphicsScene);
2009 return d->index->items(rect, mode, order, deviceTransform);
2010}
2011
2012/*!
2013 \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
2014 \overload
2015 \since 4.6
2016
2017 \brief Returns all visible items that, depending on \a mode, are
2018 either inside or intersect with the specified \a polygon, in
2019 a list sorted using \a order. In this case, "visible" defines items for which:
2020 isVisible() returns \c true, effectiveOpacity() returns a value greater than 0.0
2021 (which is fully transparent) and the parent item does not clip it.
2022
2023 The default value for \a mode is Qt::IntersectsItemShape; all items whose
2024 exact shape intersects with or is contained by \a polygon are returned.
2025
2026 \a deviceTransform is the transformation that applies to the view, and needs to
2027 be provided if the scene contains items that ignore transformations.
2028
2029 \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
2030*/
2031QList<QGraphicsItem *> QGraphicsScene::items(const QPolygonF &polygon, Qt::ItemSelectionMode mode,
2032 Qt::SortOrder order, const QTransform &deviceTransform) const
2033{
2034 Q_D(const QGraphicsScene);
2035 return d->index->items(polygon, mode, order, deviceTransform);
2036}
2037
2038/*!
2039 \fn QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode, Qt::SortOrder order, const QTransform &deviceTransform) const
2040 \overload
2041 \since 4.6
2042
2043 \brief Returns all visible items that, depending on \a mode, are
2044 either inside or intersect with the specified \a path, in a
2045 list sorted using \a order. In this case, "visible" defines items for which:
2046 isVisible() returns \c true, effectiveOpacity() returns a value greater than 0.0
2047 (which is fully transparent) and the parent item does not clip it.
2048
2049 The default value for \a mode is Qt::IntersectsItemShape; all items whose
2050 exact shape intersects with or is contained by \a path are returned.
2051
2052 \a deviceTransform is the transformation that applies to the view, and needs to
2053 be provided if the scene contains items that ignore transformations.
2054
2055 \sa itemAt(), {QGraphicsItem#Sorting}{Sorting}
2056*/
2057QList<QGraphicsItem *> QGraphicsScene::items(const QPainterPath &path, Qt::ItemSelectionMode mode,
2058 Qt::SortOrder order, const QTransform &deviceTransform) const
2059{
2060 Q_D(const QGraphicsScene);
2061 return d->index->items(path, mode, order, deviceTransform);
2062}
2063
2064/*!
2065 Returns a list of all items that collide with \a item. Collisions are
2066 determined by calling QGraphicsItem::collidesWithItem(); the collision
2067 detection is determined by \a mode. By default, all items whose shape
2068 intersects \a item or is contained inside \a item's shape are returned.
2069
2070 The items are returned in descending stacking order (i.e., the first item
2071 in the list is the uppermost item, and the last item is the lowermost
2072 item).
2073
2074 \sa items(), itemAt(), QGraphicsItem::collidesWithItem(), {QGraphicsItem#Sorting}{Sorting}
2075*/
2076QList<QGraphicsItem *> QGraphicsScene::collidingItems(const QGraphicsItem *item,
2077 Qt::ItemSelectionMode mode) const
2078{
2079 Q_D(const QGraphicsScene);
2080 if (!item) {
2081 qWarning("QGraphicsScene::collidingItems: cannot find collisions for null item");
2082 return QList<QGraphicsItem *>();
2083 }
2084
2085 // Does not support ItemIgnoresTransformations.
2086 QList<QGraphicsItem *> tmp;
2087 const auto itemsInVicinity = d->index->estimateItems(item->sceneBoundingRect(), Qt::DescendingOrder);
2088 for (QGraphicsItem *itemInVicinity : itemsInVicinity) {
2089 if (item != itemInVicinity && item->collidesWithItem(itemInVicinity, mode))
2090 tmp << itemInVicinity;
2091 }
2092 return tmp;
2093}
2094
2095/*!
2096 \since 4.6
2097
2098 Returns the topmost visible item at the specified \a position, or \nullptr
2099 if there are no items at this position.
2100
2101 \a deviceTransform is the transformation that applies to the view, and needs to
2102 be provided if the scene contains items that ignore transformations.
2103
2104 Note: See items() for a definition of which items are considered visible by this function.
2105
2106 \sa items(), collidingItems(), {QGraphicsItem#Sorting}{Sorting}
2107*/
2108QGraphicsItem *QGraphicsScene::itemAt(const QPointF &position, const QTransform &deviceTransform) const
2109{
2110 const QList<QGraphicsItem *> itemsAtPoint = items(position, Qt::IntersectsItemShape,
2111 Qt::DescendingOrder, deviceTransform);
2112 return itemsAtPoint.isEmpty() ? nullptr : itemsAtPoint.first();
2113}
2114
2115/*!
2116 \fn QGraphicsScene::itemAt(qreal x, qreal y, const QTransform &deviceTransform) const
2117 \overload
2118 \since 4.6
2119
2120 Returns the topmost visible item at the position specified by (\a x, \a
2121 y), or \nullptr if there are no items at this position.
2122
2123 \a deviceTransform is the transformation that applies to the view, and needs to
2124 be provided if the scene contains items that ignore transformations.
2125
2126 This convenience function is equivalent to calling \c
2127 {itemAt(QPointF(x, y), deviceTransform)}.
2128
2129 Note: See items() for a definition of which items are considered visible by this function.
2130*/
2131
2132/*!
2133 Returns a list of all currently selected items. The items are
2134 returned in no particular order.
2135
2136 \sa setSelectionArea()
2137*/
2138QList<QGraphicsItem *> QGraphicsScene::selectedItems() const
2139{
2140 Q_D(const QGraphicsScene);
2141
2142 // Optimization: Lazily removes items that are not selected.
2143 QGraphicsScene *that = const_cast<QGraphicsScene *>(this);
2144 QSet<QGraphicsItem *> actuallySelectedSet;
2145 for (QGraphicsItem *item : std::as_const(that->d_func()->selectedItems)) {
2146 if (item->isSelected())
2147 actuallySelectedSet << item;
2148 }
2149
2150 that->d_func()->selectedItems = actuallySelectedSet;
2151
2152 return d->selectedItems.values();
2153}
2154
2155/*!
2156 Returns the selection area that was previously set with
2157 setSelectionArea(), or an empty QPainterPath if no selection area has been
2158 set.
2159
2160 \sa setSelectionArea()
2161*/
2162QPainterPath QGraphicsScene::selectionArea() const
2163{
2164 Q_D(const QGraphicsScene);
2165 return d->selectionArea;
2166}
2167
2168/*!
2169 \since 4.6
2170
2171 Sets the selection area to \a path. All items within this area are
2172 immediately selected, and all items outside are unselected. You can get
2173 the list of all selected items by calling selectedItems().
2174
2175 \a deviceTransform is the transformation that applies to the view, and needs to
2176 be provided if the scene contains items that ignore transformations.
2177
2178 For an item to be selected, it must be marked as \e selectable
2179 (QGraphicsItem::ItemIsSelectable).
2180
2181 \sa clearSelection(), selectionArea()
2182*/
2183void QGraphicsScene::setSelectionArea(const QPainterPath &path, const QTransform &deviceTransform)
2184{
2185 setSelectionArea(path, Qt::ReplaceSelection, Qt::IntersectsItemShape, deviceTransform);
2186}
2187
2188/*!
2189 \overload
2190 \since 5.5
2191
2192 Sets the selection area to \a path using \a mode to determine if items are
2193 included in the selection area.
2194
2195 \a deviceTransform is the transformation that applies to the view, and needs to
2196 be provided if the scene contains items that ignore transformations.
2197
2198 \a selectionOperation determines what to do with the currently selected items.
2199
2200 \sa clearSelection(), selectionArea()
2201*/
2202void QGraphicsScene::setSelectionArea(const QPainterPath &path,
2203 Qt::ItemSelectionOperation selectionOperation,
2204 Qt::ItemSelectionMode mode,
2205 const QTransform &deviceTransform)
2206{
2207 Q_D(QGraphicsScene);
2208
2209 // Note: with boolean path operations, we can improve performance here
2210 // quite a lot by "growing" the old path instead of replacing it. That
2211 // allows us to only check the intersect area for changes, instead of
2212 // reevaluating the whole path over again.
2213 d->selectionArea = path;
2214
2215 QSet<QGraphicsItem *> unselectItems = d->selectedItems;
2216
2217 // Disable emitting selectionChanged() for individual items.
2218 ++d->selectionChanging;
2219 bool changed = false;
2220
2221 // Set all items in path to selected.
2222 const auto items = this->items(path, mode, Qt::DescendingOrder, deviceTransform);
2223 for (QGraphicsItem *item : items) {
2224 if (item->flags() & QGraphicsItem::ItemIsSelectable) {
2225 if (!item->isSelected())
2226 changed = true;
2227 unselectItems.remove(item);
2228 item->setSelected(true);
2229 }
2230 }
2231
2232 switch (selectionOperation) {
2233 case Qt::ReplaceSelection:
2234 // Deselect all items outside path.
2235 for (QGraphicsItem *item : std::as_const(unselectItems)) {
2236 item->setSelected(false);
2237 changed = true;
2238 }
2239 break;
2240 default:
2241 break;
2242 }
2243
2244 // Re-enable emitting selectionChanged() for individual items.
2245 --d->selectionChanging;
2246
2247 if (!d->selectionChanging && changed)
2248 emit selectionChanged();
2249}
2250
2251/*!
2252 Clears the current selection.
2253
2254 \sa setSelectionArea(), selectedItems()
2255*/
2256void QGraphicsScene::clearSelection()
2257{
2258 Q_D(QGraphicsScene);
2259
2260 // Disable emitting selectionChanged
2261 ++d->selectionChanging;
2262 // iterate over a copy, as clearing selection might invalidate selectedItems
2263 const auto selectedItems = d->selectedItems;
2264 QSet<QGraphicsItem *> stillSelectedSet;
2265
2266 for (QGraphicsItem *item : selectedItems) {
2267 item->setSelected(false);
2268 // items might override itemChange to prevent deselection
2269 if (item->isSelected())
2270 stillSelectedSet << item;
2271 }
2272 const bool changed = stillSelectedSet != selectedItems;
2273 d->selectedItems = stillSelectedSet;
2274
2275 // Re-enable emitting selectionChanged() for individual items.
2276 --d->selectionChanging;
2277
2278 if (!d->selectionChanging && changed)
2279 emit selectionChanged();
2280}
2281
2282/*!
2283 \since 4.4
2284
2285 Removes and deletes all items from the scene, but otherwise leaves the
2286 state of the scene unchanged.
2287
2288 \sa addItem()
2289*/
2290void QGraphicsScene::clear()
2291{
2292 Q_D(QGraphicsScene);
2293 // NB! We have to clear the index before deleting items; otherwise the
2294 // index might try to access dangling item pointers.
2295 d->index->clear();
2296 // NB! QGraphicsScenePrivate::unregisterTopLevelItem() removes items
2297 while (!d->topLevelItems.isEmpty())
2298 delete d->topLevelItems.first();
2299 Q_ASSERT(d->topLevelItems.isEmpty());
2300 d->lastItemCount = 0;
2301 d->allItemsIgnoreHoverEvents = true;
2302 d->allItemsUseDefaultCursor = true;
2303 d->allItemsIgnoreTouchEvents = true;
2304 d->focusOnTouch = true;
2305}
2306
2307/*!
2308 Groups all items in \a items into a new QGraphicsItemGroup, and returns a
2309 pointer to the group. The group is created with the common ancestor of \a
2310 items as its parent, and with position (0, 0). The items are all
2311 reparented to the group, and their positions and transformations are
2312 mapped to the group. If \a items is empty, this function will return an
2313 empty top-level QGraphicsItemGroup.
2314
2315 QGraphicsScene has ownership of the group item; you do not need to delete
2316 it. To dismantle (ungroup) a group, call destroyItemGroup().
2317
2318 \sa destroyItemGroup(), QGraphicsItemGroup::addToGroup()
2319*/
2320QGraphicsItemGroup *QGraphicsScene::createItemGroup(const QList<QGraphicsItem *> &items)
2321{
2322 // Build a list of the first item's ancestors
2323 QList<QGraphicsItem *> ancestors;
2324 int n = 0;
2325 if (!items.isEmpty()) {
2326 QGraphicsItem *parent = items.at(n++);
2327 while ((parent = parent->parentItem()))
2328 ancestors.append(parent);
2329 }
2330
2331 // Find the common ancestor for all items
2332 QGraphicsItem *commonAncestor = nullptr;
2333 if (!ancestors.isEmpty()) {
2334 while (n < items.size()) {
2335 int commonIndex = -1;
2336 QGraphicsItem *parent = items.at(n++);
2337 do {
2338 int index = ancestors.indexOf(parent, qMax(0, commonIndex));
2339 if (index != -1) {
2340 commonIndex = index;
2341 break;
2342 }
2343 } while ((parent = parent->parentItem()));
2344
2345 if (commonIndex == -1) {
2346 commonAncestor = nullptr;
2347 break;
2348 }
2349
2350 commonAncestor = ancestors.at(commonIndex);
2351 }
2352 }
2353
2354 // Create a new group at that level
2355 QGraphicsItemGroup *group = new QGraphicsItemGroup(commonAncestor);
2356 if (!commonAncestor)
2357 addItem(group);
2358 for (QGraphicsItem *item : items)
2359 group->addToGroup(item);
2360 return group;
2361}
2362
2363/*!
2364 Reparents all items in \a group to \a group's parent item, then removes \a
2365 group from the scene, and finally deletes it. The items' positions and
2366 transformations are mapped from the group to the group's parent.
2367
2368 \sa createItemGroup(), QGraphicsItemGroup::removeFromGroup()
2369*/
2370void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup *group)
2371{
2372 const auto items = group->childItems();
2373 for (QGraphicsItem *item : items)
2374 group->removeFromGroup(item);
2375 removeItem(group);
2376 delete group;
2377}
2378
2379/*!
2380 Adds or moves the \a item and all its children to this scene.
2381 This scene takes ownership of the \a item.
2382
2383 If the item is visible (i.e., QGraphicsItem::isVisible() returns
2384 true), QGraphicsScene will emit changed() once control goes back
2385 to the event loop.
2386
2387 If the item is already in a different scene, it will first be
2388 removed from its old scene, and then added to this scene as a
2389 top-level.
2390
2391 QGraphicsScene will send ItemSceneChange notifications to \a item
2392 while it is added to the scene. If item does not currently belong
2393 to a scene, only one notification is sent. If it does belong to
2394 scene already (i.e., it is moved to this scene), QGraphicsScene
2395 will send an addition notification as the item is removed from its
2396 previous scene.
2397
2398 If the item is a panel, the scene is active, and there is no
2399 active panel in the scene, then the item will be activated.
2400
2401 \sa removeItem(), addEllipse(), addLine(), addPath(), addPixmap(),
2402 addRect(), addText(), addWidget(), {QGraphicsItem#Sorting}{Sorting}
2403*/
2404void QGraphicsScene::addItem(QGraphicsItem *item)
2405{
2406 Q_D(QGraphicsScene);
2407 if (!item) {
2408 qWarning("QGraphicsScene::addItem: cannot add null item");
2409 return;
2410 }
2411 if (item->d_ptr->scene == this) {
2412 qWarning("QGraphicsScene::addItem: item has already been added to this scene");
2413 return;
2414 }
2415 // Remove this item from its existing scene
2416 if (QGraphicsScene *oldScene = item->d_ptr->scene)
2417 oldScene->removeItem(item);
2418
2419 // Notify the item that its scene is changing, and allow the item to
2420 // react.
2421 const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
2422 QVariant::fromValue<QGraphicsScene *>(this)));
2423 QGraphicsScene *targetScene = qvariant_cast<QGraphicsScene *>(newSceneVariant);
2424 if (targetScene != this) {
2425 if (targetScene && item->d_ptr->scene != targetScene)
2426 targetScene->addItem(item);
2427 return;
2428 }
2429
2430 if (d->unpolishedItems.isEmpty()) {
2431 QMetaMethod method = metaObject()->method(d->polishItemsIndex);
2432 method.invoke(this, Qt::QueuedConnection);
2433 }
2434 d->unpolishedItems.append(item);
2435 item->d_ptr->pendingPolish = true;
2436
2437 // Detach this item from its parent if the parent's scene is different
2438 // from this scene.
2439 if (QGraphicsItem *itemParent = item->d_ptr->parent) {
2440 if (itemParent->d_ptr->scene != this)
2441 item->setParentItem(nullptr);
2442 }
2443
2444 // Add the item to this scene
2445 item->d_func()->scene = targetScene;
2446
2447 // Add the item in the index
2448 d->index->addItem(item);
2449
2450 // Add to list of toplevels if this item is a toplevel.
2451 if (!item->d_ptr->parent)
2452 d->registerTopLevelItem(item);
2453
2454 // Add to list of items that require an update. We cannot assume that the
2455 // item is fully constructed, so calling item->update() can lead to a pure
2456 // virtual function call to boundingRect().
2457 d->markDirty(item);
2458 d->dirtyGrowingItemsBoundingRect = true;
2459
2460 // Disable selectionChanged() for individual items
2461 ++d->selectionChanging;
2462 int oldSelectedItemSize = d->selectedItems.size();
2463
2464 // Enable mouse tracking if we haven't already done so, and the item needs it.
2465 // We cannot use itemAcceptsHoverEvents_helper() here, since we need to enable
2466 // mouse tracking also if this item is temporarily blocked by a modal panel.
2467
2468 auto needsMouseTracking = [](const QGraphicsItemPrivate *item) {
2469 return item->acceptsHover
2470 || (item->isWidget && static_cast<const QGraphicsWidgetPrivate *>(item)->hasDecoration());
2471 };
2472
2473 if (d->allItemsIgnoreHoverEvents && needsMouseTracking(item->d_ptr.data())) {
2474 d->allItemsIgnoreHoverEvents = false;
2475 d->enableMouseTrackingOnViews();
2476 }
2477#ifndef QT_NO_CURSOR
2478 if (d->allItemsUseDefaultCursor && item->d_ptr->hasCursor) {
2479 d->allItemsUseDefaultCursor = false;
2480 if (d->allItemsIgnoreHoverEvents) // already enabled otherwise
2481 d->enableMouseTrackingOnViews();
2482 }
2483#endif //QT_NO_CURSOR
2484
2485 // Enable touch events if the item accepts touch events.
2486 if (d->allItemsIgnoreTouchEvents && item->d_ptr->acceptTouchEvents) {
2487 d->allItemsIgnoreTouchEvents = false;
2488 d->enableTouchEventsOnViews();
2489 }
2490
2491#ifndef QT_NO_GESTURES
2492 for (auto it = item->d_ptr->gestureContext.constBegin();
2493 it != item->d_ptr->gestureContext.constEnd(); ++it)
2494 d->grabGesture(item, it.key());
2495#endif
2496
2497 // Update selection lists
2498 if (item->isSelected())
2499 d->selectedItems << item;
2500 if (item->isWidget() && item->isVisible() && static_cast<QGraphicsWidget *>(item)->windowType() == Qt::Popup)
2501 d->addPopup(static_cast<QGraphicsWidget *>(item));
2502 if (item->isPanel() && item->isVisible() && item->panelModality() != QGraphicsItem::NonModal)
2503 d->enterModal(item);
2504
2505 // Update creation order focus chain. Make sure to leave the widget's
2506 // internal tab order intact.
2507 if (item->isWidget()) {
2508 QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
2509 if (!d->tabFocusFirst) {
2510 // No first tab focus widget - make this the first tab focus
2511 // widget.
2512 d->tabFocusFirst = widget;
2513 } else if (!widget->parentWidget() && !widget->isPanel()) {
2514 // Adding a widget that is not part of a tab focus chain.
2515 QGraphicsWidget *myNewPrev = d->tabFocusFirst->d_func()->focusPrev;
2516 myNewPrev->d_func()->focusNext = widget;
2517 widget->d_func()->focusPrev->d_func()->focusNext = d->tabFocusFirst;
2518 d->tabFocusFirst->d_func()->focusPrev = widget->d_func()->focusPrev;
2519 widget->d_func()->focusPrev = myNewPrev;
2520 }
2521 }
2522
2523 // Add all children recursively
2524 item->d_ptr->ensureSortedChildren();
2525 for (auto child : std::as_const(item->d_ptr->children))
2526 addItem(child);
2527
2528 // Resolve font and palette.
2529 item->d_ptr->resolveFont(d->font.resolveMask());
2530 item->d_ptr->resolvePalette(d->palette.resolveMask());
2531
2532
2533 // Re-enable selectionChanged() for individual items
2534 --d->selectionChanging;
2535 if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemSize)
2536 emit selectionChanged();
2537
2538 // Deliver post-change notification
2539 item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
2540
2541 // Update explicit activation
2542 bool autoActivate = true;
2543 if (!d->childExplicitActivation && item->d_ptr->explicitActivate)
2544 d->childExplicitActivation = item->d_ptr->wantsActive ? 1 : 2;
2545 if (d->childExplicitActivation && item->isPanel()) {
2546 if (d->childExplicitActivation == 1)
2547 setActivePanel(item);
2548 else
2549 autoActivate = false;
2550 d->childExplicitActivation = 0;
2551 } else if (!item->d_ptr->parent) {
2552 d->childExplicitActivation = 0;
2553 }
2554
2555 // Auto-activate this item's panel if nothing else has been activated
2556 if (autoActivate) {
2557 if (!d->lastActivePanel && !d->activePanel && item->isPanel()) {
2558 if (isActive())
2559 setActivePanel(item);
2560 else
2561 d->lastActivePanel = item;
2562 }
2563 }
2564
2565 if (item->d_ptr->flags & QGraphicsItem::ItemSendsScenePositionChanges)
2566 d->registerScenePosItem(item);
2567
2568 // Ensure that newly added items that have subfocus set, gain
2569 // focus automatically if there isn't a focus item already.
2570 if (!d->focusItem && item != d->lastFocusItem && item->focusItem() == item)
2571 item->focusItem()->setFocus();
2572
2573 d->updateInputMethodSensitivityInViews();
2574}
2575
2576/*!
2577 Creates and adds an ellipse item to the scene, and returns the item
2578 pointer. The geometry of the ellipse is defined by \a rect, and its pen
2579 and brush are initialized to \a pen and \a brush.
2580
2581 Note that the item's geometry is provided in item coordinates, and its
2582 position is initialized to (0, 0).
2583
2584 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2585 QGraphicsScene will emit changed() once control goes back to the event
2586 loop.
2587
2588 \sa addLine(), addPath(), addPixmap(), addRect(), addText(), addItem(),
2589 addWidget()
2590*/
2591QGraphicsEllipseItem *QGraphicsScene::addEllipse(const QRectF &rect, const QPen &pen, const QBrush &brush)
2592{
2593 QGraphicsEllipseItem *item = new QGraphicsEllipseItem(rect);
2594 item->setPen(pen);
2595 item->setBrush(brush);
2596 addItem(item);
2597 return item;
2598}
2599
2600/*!
2601 \fn QGraphicsEllipseItem *QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
2602 \since 4.3
2603
2604 This convenience function is equivalent to calling addEllipse(QRectF(\a x,
2605 \a y, \a w, \a h), \a pen, \a brush).
2606*/
2607
2608/*!
2609 Creates and adds a line item to the scene, and returns the item
2610 pointer. The geometry of the line is defined by \a line, and its pen
2611 is initialized to \a pen.
2612
2613 Note that the item's geometry is provided in item coordinates, and its
2614 position is initialized to (0, 0).
2615
2616 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2617 QGraphicsScene will emit changed() once control goes back to the event
2618 loop.
2619
2620 \sa addEllipse(), addPath(), addPixmap(), addRect(), addText(), addItem(),
2621 addWidget()
2622*/
2623QGraphicsLineItem *QGraphicsScene::addLine(const QLineF &line, const QPen &pen)
2624{
2625 QGraphicsLineItem *item = new QGraphicsLineItem(line);
2626 item->setPen(pen);
2627 addItem(item);
2628 return item;
2629}
2630
2631/*!
2632 \fn QGraphicsLineItem *QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen &pen)
2633 \since 4.3
2634
2635 This convenience function is equivalent to calling addLine(QLineF(\a x1,
2636 \a y1, \a x2, \a y2), \a pen).
2637*/
2638
2639/*!
2640 Creates and adds a path item to the scene, and returns the item
2641 pointer. The geometry of the path is defined by \a path, and its pen and
2642 brush are initialized to \a pen and \a brush.
2643
2644 Note that the item's geometry is provided in item coordinates, and its
2645 position is initialized to (0, 0).
2646
2647 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2648 QGraphicsScene will emit changed() once control goes back to the event
2649 loop.
2650
2651 \sa addEllipse(), addLine(), addPixmap(), addRect(), addText(), addItem(),
2652 addWidget()
2653*/
2654QGraphicsPathItem *QGraphicsScene::addPath(const QPainterPath &path, const QPen &pen, const QBrush &brush)
2655{
2656 QGraphicsPathItem *item = new QGraphicsPathItem(path);
2657 item->setPen(pen);
2658 item->setBrush(brush);
2659 addItem(item);
2660 return item;
2661}
2662
2663/*!
2664 Creates and adds a pixmap item to the scene, and returns the item
2665 pointer. The pixmap is defined by \a pixmap.
2666
2667 Note that the item's geometry is provided in item coordinates, and its
2668 position is initialized to (0, 0).
2669
2670 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2671 QGraphicsScene will emit changed() once control goes back to the event
2672 loop.
2673
2674 \sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
2675 addWidget()
2676*/
2677QGraphicsPixmapItem *QGraphicsScene::addPixmap(const QPixmap &pixmap)
2678{
2679 QGraphicsPixmapItem *item = new QGraphicsPixmapItem(pixmap);
2680 addItem(item);
2681 return item;
2682}
2683
2684/*!
2685 Creates and adds a polygon item to the scene, and returns the item
2686 pointer. The polygon is defined by \a polygon, and its pen and
2687 brush are initialized to \a pen and \a brush.
2688
2689 Note that the item's geometry is provided in item coordinates, and its
2690 position is initialized to (0, 0).
2691
2692 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2693 QGraphicsScene will emit changed() once control goes back to the event
2694 loop.
2695
2696 \sa addEllipse(), addLine(), addPath(), addRect(), addText(), addItem(),
2697 addWidget()
2698*/
2699QGraphicsPolygonItem *QGraphicsScene::addPolygon(const QPolygonF &polygon,
2700 const QPen &pen, const QBrush &brush)
2701{
2702 QGraphicsPolygonItem *item = new QGraphicsPolygonItem(polygon);
2703 item->setPen(pen);
2704 item->setBrush(brush);
2705 addItem(item);
2706 return item;
2707}
2708
2709/*!
2710 Creates and adds a rectangle item to the scene, and returns the item
2711 pointer. The geometry of the rectangle is defined by \a rect, and its pen
2712 and brush are initialized to \a pen and \a brush.
2713
2714 Note that the item's geometry is provided in item coordinates, and its
2715 position is initialized to (0, 0). For example, if a QRect(50, 50, 100,
2716 100) is added, its top-left corner will be at (50, 50) relative to the
2717 origin in the item's coordinate system.
2718
2719 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2720 QGraphicsScene will emit changed() once control goes back to the event
2721 loop.
2722
2723 \sa addEllipse(), addLine(), addPixmap(), addText(), addItem(), addWidget()
2724*/
2725QGraphicsRectItem *QGraphicsScene::addRect(const QRectF &rect, const QPen &pen, const QBrush &brush)
2726{
2727 QGraphicsRectItem *item = new QGraphicsRectItem(rect);
2728 item->setPen(pen);
2729 item->setBrush(brush);
2730 addItem(item);
2731 return item;
2732}
2733
2734/*!
2735 \fn QGraphicsRectItem *QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen &pen, const QBrush &brush)
2736 \since 4.3
2737
2738 This convenience function is equivalent to calling addRect(QRectF(\a x,
2739 \a y, \a w, \a h), \a pen, \a brush).
2740*/
2741
2742/*!
2743 Creates and adds a text item to the scene, and returns the item
2744 pointer. The text string is initialized to \a text, and its font
2745 is initialized to \a font.
2746
2747 The item's position is initialized to (0, 0).
2748
2749 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2750 QGraphicsScene will emit changed() once control goes back to the event
2751 loop.
2752
2753 \sa addEllipse(), addLine(), addPixmap(), addRect(), addItem(), addWidget()
2754*/
2755QGraphicsTextItem *QGraphicsScene::addText(const QString &text, const QFont &font)
2756{
2757 QGraphicsTextItem *item = new QGraphicsTextItem(text);
2758 item->setFont(font);
2759 addItem(item);
2760 return item;
2761}
2762
2763/*!
2764 Creates and adds a QGraphicsSimpleTextItem to the scene, and returns the
2765 item pointer. The text string is initialized to \a text, and its font is
2766 initialized to \a font.
2767
2768 The item's position is initialized to (0, 0).
2769
2770 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2771 QGraphicsScene will emit changed() once control goes back to the event
2772 loop.
2773
2774 \sa addEllipse(), addLine(), addPixmap(), addRect(), addItem(), addWidget()
2775*/
2776QGraphicsSimpleTextItem *QGraphicsScene::addSimpleText(const QString &text, const QFont &font)
2777{
2778 QGraphicsSimpleTextItem *item = new QGraphicsSimpleTextItem(text);
2779 item->setFont(font);
2780 addItem(item);
2781 return item;
2782}
2783
2784/*!
2785 Creates a new QGraphicsProxyWidget for \a widget, adds it to the scene,
2786 and returns a pointer to the proxy. \a wFlags set the default window flags
2787 for the embedding proxy widget.
2788
2789 The item's position is initialized to (0, 0).
2790
2791 If the item is visible (i.e., QGraphicsItem::isVisible() returns \c true),
2792 QGraphicsScene will emit changed() once control goes back to the event
2793 loop.
2794
2795 Note that widgets with the Qt::WA_PaintOnScreen widget attribute
2796 set and widgets that wrap an external application or controller
2797 are not supported. Examples are QOpenGLWidget and QAxWidget.
2798
2799 \sa addEllipse(), addLine(), addPixmap(), addRect(),
2800 addText(), addSimpleText(), addItem()
2801*/
2802QGraphicsProxyWidget *QGraphicsScene::addWidget(QWidget *widget, Qt::WindowFlags wFlags)
2803{
2804 QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(nullptr, wFlags);
2805 proxy->setWidget(widget);
2806 addItem(proxy);
2807 return proxy;
2808}
2809
2810/*!
2811 Removes the item \a item and all its children from the scene. The
2812 ownership of \a item is passed on to the caller (i.e.,
2813 QGraphicsScene will no longer delete \a item when destroyed).
2814
2815 \sa addItem()
2816*/
2817void QGraphicsScene::removeItem(QGraphicsItem *item)
2818{
2819 // ### Refactoring: This function shares much functionality with _q_removeItemLater()
2820 Q_D(QGraphicsScene);
2821 if (!item) {
2822 qWarning("QGraphicsScene::removeItem: cannot remove 0-item");
2823 return;
2824 }
2825 if (item->scene() != this) {
2826 qWarning("QGraphicsScene::removeItem: item %p's scene (%p)"
2827 " is different from this scene (%p)",
2828 item, item->scene(), this);
2829 return;
2830 }
2831
2832 // Notify the item that it's scene is changing to 0, allowing the item to
2833 // react.
2834 const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange,
2835 QVariant::fromValue<QGraphicsScene *>(0)));
2836 QGraphicsScene *targetScene = qvariant_cast<QGraphicsScene *>(newSceneVariant);
2837 if (targetScene != nullptr && targetScene != this) {
2838 targetScene->addItem(item);
2839 return;
2840 }
2841
2842 d->removeItemHelper(item);
2843
2844 // Deliver post-change notification
2845 item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant);
2846
2847 d->updateInputMethodSensitivityInViews();
2848}
2849
2850/*!
2851 When the scene is active, this functions returns the scene's current focus
2852 item, or \nullptr if no item currently has focus. When the scene is inactive,
2853 this functions returns the item that will gain input focus when the scene
2854 becomes active.
2855
2856 The focus item receives keyboard input when the scene receives a
2857 key event.
2858
2859 \sa setFocusItem(), QGraphicsItem::hasFocus(), isActive()
2860*/
2861QGraphicsItem *QGraphicsScene::focusItem() const
2862{
2863 Q_D(const QGraphicsScene);
2864 return isActive() ? d->focusItem : d->passiveFocusItem;
2865}
2866
2867/*!
2868 Sets the scene's focus item to \a item, with the focus reason \a
2869 focusReason, after removing focus from any previous item that may have had
2870 focus.
2871
2872 If \a item is \nullptr, or if it either does not accept focus (i.e., it does not
2873 have the QGraphicsItem::ItemIsFocusable flag enabled), or is not visible
2874 or not enabled, this function only removes focus from any previous
2875 focusitem.
2876
2877 If item is not \nullptr, and the scene does not currently have focus (i.e.,
2878 hasFocus() returns \c false), this function will call setFocus()
2879 automatically.
2880
2881 \sa focusItem(), hasFocus(), setFocus()
2882*/
2883void QGraphicsScene::setFocusItem(QGraphicsItem *item, Qt::FocusReason focusReason)
2884{
2885 Q_D(QGraphicsScene);
2886 if (item)
2887 item->setFocus(focusReason);
2888 else
2889 d->setFocusItemHelper(item, focusReason);
2890}
2891
2892/*!
2893 Returns \c true if the scene has focus; otherwise returns \c false. If the scene
2894 has focus, it will forward key events from QKeyEvent to any item that
2895 has focus.
2896
2897 \sa setFocus(), setFocusItem()
2898*/
2899bool QGraphicsScene::hasFocus() const
2900{
2901 Q_D(const QGraphicsScene);
2902 return d->hasFocus;
2903}
2904
2905/*!
2906 Sets focus on the scene by sending a QFocusEvent to the scene, passing \a
2907 focusReason as the reason. If the scene regains focus after having
2908 previously lost it while an item had focus, the last focus item will
2909 receive focus with \a focusReason as the reason.
2910
2911 If the scene already has focus, this function does nothing.
2912
2913 \sa hasFocus(), clearFocus(), setFocusItem()
2914*/
2915void QGraphicsScene::setFocus(Qt::FocusReason focusReason)
2916{
2917 Q_D(QGraphicsScene);
2918 if (d->hasFocus || !isActive())
2919 return;
2920 QFocusEvent event(QEvent::FocusIn, focusReason);
2921 QCoreApplication::sendEvent(this, &event);
2922}
2923
2924/*!
2925 Clears focus from the scene. If any item has focus when this function is
2926 called, it will lose focus, and regain focus again once the scene regains
2927 focus.
2928
2929 A scene that does not have focus ignores key events.
2930
2931 \sa hasFocus(), setFocus(), setFocusItem()
2932*/
2933void QGraphicsScene::clearFocus()
2934{
2935 Q_D(QGraphicsScene);
2936 if (d->hasFocus) {
2937 d->hasFocus = false;
2938 d->passiveFocusItem = d->focusItem;
2939 setFocusItem(nullptr, Qt::OtherFocusReason);
2940 }
2941}
2942
2943/*!
2944 \property QGraphicsScene::stickyFocus
2945 \brief whether clicking into the scene background will clear focus
2946
2947 \since 4.6
2948
2949 In a QGraphicsScene with stickyFocus set to true, focus will remain
2950 unchanged when the user clicks into the scene background or on an item
2951 that does not accept focus. Otherwise, focus will be cleared.
2952
2953 By default, this property is \c false.
2954
2955 Focus changes in response to a mouse press. You can reimplement
2956 mousePressEvent() in a subclass of QGraphicsScene to toggle this property
2957 based on where the user has clicked.
2958
2959 \sa clearFocus(), setFocusItem()
2960*/
2961void QGraphicsScene::setStickyFocus(bool enabled)
2962{
2963 Q_D(QGraphicsScene);
2964 d->stickyFocus = enabled;
2965}
2966bool QGraphicsScene::stickyFocus() const
2967{
2968 Q_D(const QGraphicsScene);
2969 return d->stickyFocus;
2970}
2971
2972/*!
2973 Returns the current mouse grabber item, or \nullptr if no item is
2974 currently grabbing the mouse. The mouse grabber item is the item
2975 that receives all mouse events sent to the scene.
2976
2977 An item becomes a mouse grabber when it receives and accepts a
2978 mouse press event, and it stays the mouse grabber until either of
2979 the following events occur:
2980
2981 \list
2982 \li If the item receives a mouse release event when there are no other
2983 buttons pressed, it loses the mouse grab.
2984 \li If the item becomes invisible (i.e., someone calls \c {item->setVisible(false)}),
2985 or if it becomes disabled (i.e., someone calls \c {item->setEnabled(false)}),
2986 it loses the mouse grab.
2987 \li If the item is removed from the scene, it loses the mouse grab.
2988 \endlist
2989
2990 If the item loses its mouse grab, the scene will ignore all mouse events
2991 until a new item grabs the mouse (i.e., until a new item receives a mouse
2992 press event).
2993*/
2994QGraphicsItem *QGraphicsScene::mouseGrabberItem() const
2995{
2996 Q_D(const QGraphicsScene);
2997 return !d->mouseGrabberItems.isEmpty() ? d->mouseGrabberItems.last() : 0;
2998}
2999
3000/*!
3001 \property QGraphicsScene::backgroundBrush
3002 \brief the background brush of the scene.
3003
3004 Set this property to changes the scene's background to a different color,
3005 gradient or texture. The default background brush is Qt::NoBrush. The
3006 background is drawn before (behind) the items.
3007
3008 Example:
3009
3010 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 3
3011
3012 QGraphicsScene::render() calls drawBackground() to draw the scene
3013 background. For more detailed control over how the background is drawn,
3014 you can reimplement drawBackground() in a subclass of QGraphicsScene.
3015*/
3016QBrush QGraphicsScene::backgroundBrush() const
3017{
3018 Q_D(const QGraphicsScene);
3019 return d->backgroundBrush;
3020}
3021void QGraphicsScene::setBackgroundBrush(const QBrush &brush)
3022{
3023 Q_D(QGraphicsScene);
3024 d->backgroundBrush = brush;
3025 for (QGraphicsView *view : std::as_const(d->views)) {
3026 view->resetCachedContent();
3027 view->viewport()->update();
3028 }
3029 update();
3030}
3031
3032/*!
3033 \property QGraphicsScene::foregroundBrush
3034 \brief the foreground brush of the scene.
3035
3036 Change this property to set the scene's foreground to a different
3037 color, gradient or texture.
3038
3039 The foreground is drawn after (on top of) the items. The default
3040 foreground brush is Qt::NoBrush ( i.e. the foreground is not
3041 drawn).
3042
3043 Example:
3044
3045 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 4
3046
3047 QGraphicsScene::render() calls drawForeground() to draw the scene
3048 foreground. For more detailed control over how the foreground is
3049 drawn, you can reimplement the drawForeground() function in a
3050 QGraphicsScene subclass.
3051*/
3052QBrush QGraphicsScene::foregroundBrush() const
3053{
3054 Q_D(const QGraphicsScene);
3055 return d->foregroundBrush;
3056}
3057void QGraphicsScene::setForegroundBrush(const QBrush &brush)
3058{
3059 Q_D(QGraphicsScene);
3060 d->foregroundBrush = brush;
3061 const auto views_ = views();
3062 for (QGraphicsView *view : views_)
3063 view->viewport()->update();
3064 update();
3065}
3066
3067/*!
3068 This method is used by input methods to query a set of properties of
3069 the scene to be able to support complex input method operations as support
3070 for surrounding text and reconversions.
3071
3072 The \a query parameter specifies which property is queried.
3073
3074 \sa QWidget::inputMethodQuery()
3075*/
3076QVariant QGraphicsScene::inputMethodQuery(Qt::InputMethodQuery query) const
3077{
3078 Q_D(const QGraphicsScene);
3079 if (!d->focusItem || !(d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
3080 return QVariant();
3081 const QTransform matrix = d->focusItem->sceneTransform();
3082 QVariant value = d->focusItem->inputMethodQuery(query);
3083 if (value.userType() == QMetaType::QRectF)
3084 value = matrix.mapRect(value.toRectF());
3085 else if (value.userType() == QMetaType::QPointF)
3086 value = matrix.map(value.toPointF());
3087 else if (value.userType() == QMetaType::QRect)
3088 value = matrix.mapRect(value.toRect());
3089 else if (value.userType() == QMetaType::QPoint)
3090 value = matrix.map(value.toPoint());
3091 return value;
3092}
3093
3094/*!
3095 \fn void QGraphicsScene::update(const QRectF &rect)
3096 Schedules a redraw of the area \a rect on the scene.
3097
3098 \sa sceneRect(), changed()
3099*/
3100void QGraphicsScene::update(const QRectF &rect)
3101{
3102 Q_D(QGraphicsScene);
3103 if (d->updateAll || (rect.isEmpty() && !rect.isNull()))
3104 return;
3105
3106 // Check if anyone's connected; if not, we can send updates directly to
3107 // the views. Otherwise or if there are no views, use old behavior.
3108 bool directUpdates = !(d->isSignalConnected(d->changedSignalIndex)) && !d->views.isEmpty();
3109 if (rect.isNull()) {
3110 d->updateAll = true;
3111 d->updatedRects.clear();
3112 if (directUpdates) {
3113 // Update all views.
3114 for (auto view : std::as_const(d->views))
3115 view->d_func()->fullUpdatePending = true;
3116 }
3117 } else {
3118 if (directUpdates) {
3119 // Update all views.
3120 for (auto view : std::as_const(d->views)) {
3121 if (view->isTransformed())
3122 view->d_func()->updateRectF(view->viewportTransform().mapRect(rect));
3123 else
3124 view->d_func()->updateRectF(rect);
3125 }
3126 } else {
3127 d->updatedRects.insert(rect);
3128 }
3129 }
3130
3131 if (!d->calledEmitUpdated) {
3132 d->calledEmitUpdated = true;
3133 QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection);
3134 }
3135}
3136
3137/*!
3138 \fn void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h)
3139 \overload
3140 \since 4.3
3141
3142 This function is equivalent to calling update(QRectF(\a x, \a y, \a w,
3143 \a h));
3144*/
3145
3146/*!
3147 Invalidates and schedules a redraw of the \a layers in \a rect on the
3148 scene. Any cached content in \a layers is unconditionally invalidated and
3149 redrawn.
3150
3151 You can use this function overload to notify QGraphicsScene of changes to
3152 the background or the foreground of the scene. This function is commonly
3153 used for scenes with tile-based backgrounds to notify changes when
3154 QGraphicsView has enabled
3155 \l{QGraphicsView::CacheBackground}{CacheBackground}.
3156
3157 Example:
3158
3159 \snippet code/src_gui_graphicsview_qgraphicsscene.cpp 5
3160
3161 Note that QGraphicsView currently supports background caching only (see
3162 QGraphicsView::CacheBackground). This function is equivalent to calling
3163 update() if any layer but BackgroundLayer is passed.
3164
3165 \sa QGraphicsView::resetCachedContent()
3166*/
3167void QGraphicsScene::invalidate(const QRectF &rect, SceneLayers layers)
3168{
3169 const auto views_ = views();
3170 for (QGraphicsView *view : views_)
3171 view->invalidateScene(rect, layers);
3172 update(rect);
3173}
3174
3175/*!
3176 \fn void QGraphicsScene::invalidate(qreal x, qreal y, qreal w, qreal h, SceneLayers layers)
3177 \overload
3178 \since 4.3
3179
3180 This convenience function is equivalent to calling invalidate(QRectF(\a x, \a
3181 y, \a w, \a h), \a layers);
3182*/
3183
3184/*!
3185 Returns a list of all the views that display this scene.
3186
3187 \sa QGraphicsView::scene()
3188*/
3189QList <QGraphicsView *> QGraphicsScene::views() const
3190{
3191 Q_D(const QGraphicsScene);
3192 return d->views;
3193}
3194
3195/*!
3196 This slot \e advances the scene by one step, by calling
3197 QGraphicsItem::advance() for all items on the scene. This is done in two
3198 phases: in the first phase, all items are notified that the scene is about
3199 to change, and in the second phase all items are notified that they can
3200 move. In the first phase, QGraphicsItem::advance() is called passing a
3201 value of 0 as an argument, and 1 is passed in the second phase.
3202
3203 Note that you can also use the \l{The Animation Framework}{Animation
3204 Framework} for animations.
3205
3206 \sa QGraphicsItem::advance(), QTimeLine
3207*/
3208void QGraphicsScene::advance()
3209{
3210 for (int i = 0; i < 2; ++i) {
3211 const auto items_ = items();
3212 for (QGraphicsItem *item : items_)
3213 item->advance(i);
3214 }
3215}
3216
3217/*!
3218 Processes the event \a event, and dispatches it to the respective
3219 event handlers.
3220
3221 In addition to calling the convenience event handlers, this
3222 function is responsible for converting mouse move events to hover
3223 events for when there is no mouse grabber item. Hover events are
3224 delivered directly to items; there is no convenience function for
3225 them.
3226
3227 Unlike QWidget, QGraphicsScene does not have the convenience functions
3228 \l{QWidget::}{enterEvent()} and \l{QWidget::}{leaveEvent()}. Use this
3229 function to obtain those events instead.
3230
3231 Returns \c true if \a event has been recognized and processed; otherwise,
3232 returns \c false.
3233
3234 \sa contextMenuEvent(), keyPressEvent(), keyReleaseEvent(),
3235 mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(),
3236 mouseDoubleClickEvent(), focusInEvent(), focusOutEvent()
3237*/
3238bool QGraphicsScene::event(QEvent *event)
3239{
3240 Q_D(QGraphicsScene);
3241
3242 switch (event->type()) {
3243 case QEvent::GraphicsSceneMousePress:
3244 case QEvent::GraphicsSceneMouseMove:
3245 case QEvent::GraphicsSceneMouseRelease:
3246 case QEvent::GraphicsSceneMouseDoubleClick:
3247 case QEvent::GraphicsSceneHoverEnter:
3248 case QEvent::GraphicsSceneHoverLeave:
3249 case QEvent::GraphicsSceneHoverMove:
3250 case QEvent::TouchBegin:
3251 case QEvent::TouchUpdate:
3252 case QEvent::TouchEnd:
3253 // Reset the under-mouse list to ensure that this event gets fresh
3254 // item-under-mouse data. Be careful about this list; if people delete
3255 // items from inside event handlers, this list can quickly end up
3256 // having stale pointers in it. We need to clear it before dispatching
3257 // events that use it.
3258 // ### this should only be cleared if we received a new mouse move event,
3259 // which relies on us fixing the replay mechanism in QGraphicsView.
3260 d->cachedItemsUnderMouse.clear();
3261 break;
3262 default:
3263 break;
3264 }
3265
3266 switch (event->type()) {
3267 case QEvent::GraphicsSceneDragEnter:
3268 dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
3269 break;
3270 case QEvent::GraphicsSceneDragMove:
3271 dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
3272 break;
3273 case QEvent::GraphicsSceneDragLeave:
3274 dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
3275 break;
3276 case QEvent::GraphicsSceneDrop:
3277 dropEvent(static_cast<QGraphicsSceneDragDropEvent *>(event));
3278 break;
3279 case QEvent::GraphicsSceneContextMenu:
3280 contextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent *>(event));
3281 break;
3282 case QEvent::KeyPress:
3283 if (!d->focusItem) {
3284 QKeyEvent *k = static_cast<QKeyEvent *>(event);
3285 if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
3286 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
3287 bool res = false;
3288 if (k->key() == Qt::Key_Backtab
3289 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier))) {
3290 res = focusNextPrevChild(false);
3291 } else if (k->key() == Qt::Key_Tab) {
3292 res = focusNextPrevChild(true);
3293 }
3294 if (!res)
3295 event->ignore();
3296 return true;
3297 }
3298 }
3299 }
3300 keyPressEvent(static_cast<QKeyEvent *>(event));
3301 break;
3302 case QEvent::KeyRelease:
3303 keyReleaseEvent(static_cast<QKeyEvent *>(event));
3304 break;
3305 case QEvent::ShortcutOverride: {
3306 QGraphicsItem *parent = focusItem();
3307 while (parent) {
3308 d->sendEvent(parent, event);
3309 if (event->isAccepted())
3310 return true;
3311 parent = parent->parentItem();
3312 }
3313 }
3314 return false;
3315 case QEvent::GraphicsSceneMouseMove:
3316 {
3317 QGraphicsSceneMouseEvent *mouseEvent = static_cast<QGraphicsSceneMouseEvent *>(event);
3318 d->lastSceneMousePos = mouseEvent->scenePos();
3319 mouseMoveEvent(mouseEvent);
3320 break;
3321 }
3322 case QEvent::GraphicsSceneMousePress:
3323 mousePressEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
3324 break;
3325 case QEvent::GraphicsSceneMouseRelease:
3326 mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
3327 break;
3328 case QEvent::GraphicsSceneMouseDoubleClick:
3329 mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent *>(event));
3330 break;
3331 case QEvent::GraphicsSceneWheel:
3332 wheelEvent(static_cast<QGraphicsSceneWheelEvent *>(event));
3333 break;
3334 case QEvent::FocusIn:
3335 focusInEvent(static_cast<QFocusEvent *>(event));
3336 break;
3337 case QEvent::FocusOut:
3338 focusOutEvent(static_cast<QFocusEvent *>(event));
3339 break;
3340 case QEvent::GraphicsSceneHoverEnter:
3341 case QEvent::GraphicsSceneHoverLeave:
3342 case QEvent::GraphicsSceneHoverMove:
3343 {
3344 QGraphicsSceneHoverEvent *hoverEvent = static_cast<QGraphicsSceneHoverEvent *>(event);
3345 d->lastSceneMousePos = hoverEvent->scenePos();
3346 d->dispatchHoverEvent(hoverEvent);
3347 break;
3348 }
3349 case QEvent::Leave:
3350 Q_ASSERT_X(false, "QGraphicsScene::event",
3351 "QGraphicsScene must not receive QEvent::Leave, use GraphicsSceneLeave");
3352 break;
3353 case QEvent::GraphicsSceneLeave:
3354 {
3355 auto *leaveEvent = static_cast<QGraphicsSceneEvent*>(event);
3356 d->leaveScene(leaveEvent->widget());
3357 break;
3358 }
3359 case QEvent::GraphicsSceneHelp:
3360 helpEvent(static_cast<QGraphicsSceneHelpEvent *>(event));
3361 break;
3362 case QEvent::InputMethod:
3363 inputMethodEvent(static_cast<QInputMethodEvent *>(event));
3364 break;
3365 case QEvent::WindowActivate:
3366 if (!d->activationRefCount++) {
3367 if (d->lastActivePanel) {
3368 // Activate the last panel.
3369 d->setActivePanelHelper(d->lastActivePanel, true);
3370 } else if (d->tabFocusFirst && d->tabFocusFirst->isPanel()) {
3371 // Activate the panel of the first item in the tab focus
3372 // chain.
3373 d->setActivePanelHelper(d->tabFocusFirst, true);
3374 } else {
3375 // Activate all toplevel items.
3376 QEvent event(QEvent::WindowActivate);
3377 const auto items_ = items();
3378 for (QGraphicsItem *item : items_) {
3379 if (item->isVisible() && !item->isPanel() && !item->parentItem())
3380 sendEvent(item, &event);
3381 }
3382 }
3383 }
3384 break;
3385 case QEvent::WindowDeactivate:
3386 if (!--d->activationRefCount) {
3387 if (d->activePanel) {
3388 // Deactivate the active panel (but keep it so we can
3389 // reactivate it later).
3390 QGraphicsItem *lastActivePanel = d->activePanel;
3391 d->setActivePanelHelper(nullptr, true);
3392 d->lastActivePanel = lastActivePanel;
3393 } else {
3394 // Activate all toplevel items.
3395 QEvent event(QEvent::WindowDeactivate);
3396 const auto items_ = items();
3397 for (QGraphicsItem *item : items_) {
3398 if (item->isVisible() && !item->isPanel() && !item->parentItem())
3399 sendEvent(item, &event);
3400 }
3401 }
3402 }
3403 break;
3404 case QEvent::ApplicationFontChange: {
3405 // Resolve the existing scene font.
3406 d->resolveFont();
3407 break;
3408 }
3409 case QEvent::FontChange:
3410 // Update the entire scene when the font changes.
3411 update();
3412 break;
3413 case QEvent::ApplicationPaletteChange: {
3414 // Resolve the existing scene palette.
3415 d->resolvePalette();
3416 break;
3417 }
3418 case QEvent::PaletteChange:
3419 // Update the entire scene when the palette changes.
3420 update();
3421 break;
3422 case QEvent::StyleChange:
3423 // Reresolve all widgets' styles. Update all top-level widgets'
3424 // geometries that do not have an explicit style set.
3425 update();
3426 break;
3427 case QEvent::StyleAnimationUpdate:
3428 // Because QGraphicsItem is not a QObject, QStyle driven
3429 // animations are forced to update the whole scene
3430 update();
3431 break;
3432 case QEvent::TouchBegin:
3433 case QEvent::TouchUpdate:
3434 case QEvent::TouchEnd:
3435 d->touchEventHandler(static_cast<QTouchEvent *>(event));
3436 break;
3437#ifndef QT_NO_GESTURES
3438 case QEvent::Gesture:
3439 case QEvent::GestureOverride:
3440 d->gestureEventHandler(static_cast<QGestureEvent *>(event));
3441 break;
3442#endif // QT_NO_GESTURES
3443 default:
3444 return QObject::event(event);
3445 }
3446 return true;
3447}
3448
3449/*!
3450 \reimp
3451
3452 QGraphicsScene filters QApplication's events to detect palette and font
3453 changes.
3454*/
3455bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event)
3456{
3457 if (watched != qApp)
3458 return false;
3459
3460 switch (event->type()) {
3461 case QEvent::ApplicationPaletteChange:
3462 QCoreApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange));
3463 break;
3464 case QEvent::ApplicationFontChange:
3465 QCoreApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange));
3466 break;
3467 default:
3468 break;
3469 }
3470 return false;
3471}
3472
3473/*!
3474 This event handler, for event \a contextMenuEvent, can be reimplemented in
3475 a subclass to receive context menu events. The default implementation
3476 forwards the event to the topmost visible item that accepts context menu events at
3477 the position of the event. If no items accept context menu events at this
3478 position, the event is ignored.
3479
3480 Note: See items() for a definition of which items are considered visible by this function.
3481
3482 \sa QGraphicsItem::contextMenuEvent()
3483*/
3484void QGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent)
3485{
3486 Q_D(QGraphicsScene);
3487 // Ignore by default.
3488 contextMenuEvent->ignore();
3489
3490 // Send the event to all items at this position until one item accepts the
3491 // event.
3492 const auto items = d->itemsAtPosition(contextMenuEvent->screenPos(),
3493 contextMenuEvent->scenePos(),
3494 contextMenuEvent->widget());
3495 for (QGraphicsItem *item : items) {
3496 contextMenuEvent->setPos(item->d_ptr->genericMapFromScene(contextMenuEvent->scenePos(),
3497 contextMenuEvent->widget()));
3498 contextMenuEvent->accept();
3499 if (!d->sendEvent(item, contextMenuEvent))
3500 break;
3501
3502 if (contextMenuEvent->isAccepted())
3503 break;
3504 }
3505}
3506
3507/*!
3508 This event handler, for event \a event, can be reimplemented in a subclass
3509 to receive drag enter events for the scene.
3510
3511 The default implementation accepts the event and prepares the scene to
3512 accept drag move events.
3513
3514 \sa QGraphicsItem::dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(),
3515 dropEvent()
3516*/
3517void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
3518{
3519 Q_D(QGraphicsScene);
3520 d->dragDropItem = nullptr;
3521 d->lastDropAction = Qt::IgnoreAction;
3522 event->accept();
3523}
3524
3525/*!
3526 This event handler, for event \a event, can be reimplemented in a subclass
3527 to receive drag move events for the scene.
3528
3529 Note: See items() for a definition of which items are considered visible by this function.
3530
3531 \sa QGraphicsItem::dragMoveEvent(), dragEnterEvent(), dragLeaveEvent(),
3532 dropEvent()
3533*/
3534void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
3535{
3536 Q_D(QGraphicsScene);
3537 event->ignore();
3538
3539 if (!d->mouseGrabberItems.isEmpty()) {
3540 // Mouse grabbers that start drag events lose the mouse grab.
3541 d->clearMouseGrabber();
3542 d->mouseGrabberButtonDownPos.clear();
3543 d->mouseGrabberButtonDownScenePos.clear();
3544 d->mouseGrabberButtonDownScreenPos.clear();
3545 }
3546
3547 bool eventDelivered = false;
3548
3549 // Find the topmost enabled items under the cursor. They are all
3550 // candidates for accepting drag & drop events.
3551 const auto items = d->itemsAtPosition(event->screenPos(),
3552 event->scenePos(),
3553 event->widget());
3554 for (QGraphicsItem *item : items) {
3555 if (!item->isEnabled() || !item->acceptDrops())
3556 continue;
3557
3558 if (item != d->dragDropItem) {
3559 // Enter the new drag drop item. If it accepts the event, we send
3560 // the leave to the parent item.
3561 QGraphicsSceneDragDropEvent dragEnter(QEvent::GraphicsSceneDragEnter);
3562 d->cloneDragDropEvent(&dragEnter, event);
3563 dragEnter.setDropAction(event->proposedAction());
3564 d->sendDragDropEvent(item, &dragEnter);
3565 event->setAccepted(dragEnter.isAccepted());
3566 event->setDropAction(dragEnter.dropAction());
3567 if (!event->isAccepted()) {
3568 // Propagate to the item under
3569 continue;
3570 }
3571
3572 d->lastDropAction = event->dropAction();
3573
3574 if (d->dragDropItem) {
3575 // Leave the last drag drop item. A perfect implementation
3576 // would set the position of this event to the point where
3577 // this event and the last event intersect with the item's
3578 // shape, but that's not easy to do. :-)
3579 QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
3580 d->cloneDragDropEvent(&dragLeave, event);
3581 d->sendDragDropEvent(d->dragDropItem, &dragLeave);
3582 }
3583
3584 // We've got a new drag & drop item
3585 d->dragDropItem = item;
3586 }
3587
3588 // Send the move event.
3589 event->setDropAction(d->lastDropAction);
3590 event->accept();
3591 d->sendDragDropEvent(item, event);
3592 if (event->isAccepted())
3593 d->lastDropAction = event->dropAction();
3594 eventDelivered = true;
3595 break;
3596 }
3597
3598 if (!eventDelivered) {
3599 if (d->dragDropItem) {
3600 // Leave the last drag drop item
3601 QGraphicsSceneDragDropEvent dragLeave(QEvent::GraphicsSceneDragLeave);
3602 d->cloneDragDropEvent(&dragLeave, event);
3603 d->sendDragDropEvent(d->dragDropItem, &dragLeave);
3604 d->dragDropItem = nullptr;
3605 }
3606 // Propagate
3607 event->setDropAction(Qt::IgnoreAction);
3608 }
3609}
3610
3611/*!
3612 This event handler, for event \a event, can be reimplemented in a subclass
3613 to receive drag leave events for the scene.
3614
3615 \sa QGraphicsItem::dragLeaveEvent(), dragEnterEvent(), dragMoveEvent(),
3616 dropEvent()
3617*/
3618void QGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
3619{
3620 Q_D(QGraphicsScene);
3621 if (d->dragDropItem) {
3622 // Leave the last drag drop item
3623 d->sendDragDropEvent(d->dragDropItem, event);
3624 d->dragDropItem = nullptr;
3625 }
3626}
3627
3628/*!
3629 This event handler, for event \a event, can be reimplemented in a subclass
3630 to receive drop events for the scene.
3631
3632 \sa QGraphicsItem::dropEvent(), dragEnterEvent(), dragMoveEvent(),
3633 dragLeaveEvent()
3634*/
3635void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
3636{
3637 Q_UNUSED(event);
3638 Q_D(QGraphicsScene);
3639 if (d->dragDropItem) {
3640 // Drop on the last drag drop item
3641 d->sendDragDropEvent(d->dragDropItem, event);
3642 d->dragDropItem = nullptr;
3643 }
3644}
3645
3646/*!
3647 This event handler, for event \a focusEvent, can be reimplemented in a
3648 subclass to receive focus in events.
3649
3650 The default implementation sets focus on the scene, and then on the last
3651 focus item.
3652
3653 \sa QGraphicsItem::focusOutEvent()
3654*/
3655void QGraphicsScene::focusInEvent(QFocusEvent *focusEvent)
3656{
3657 Q_D(QGraphicsScene);
3658
3659 d->hasFocus = true;
3660 switch (focusEvent->reason()) {
3661 case Qt::TabFocusReason:
3662 if (!focusNextPrevChild(true))
3663 focusEvent->ignore();
3664 break;
3665 case Qt::BacktabFocusReason:
3666 if (!focusNextPrevChild(false))
3667 focusEvent->ignore();
3668 break;
3669 default:
3670 if (d->passiveFocusItem) {
3671 // Set focus on the last focus item
3672 setFocusItem(d->passiveFocusItem, focusEvent->reason());
3673 }
3674 break;
3675 }
3676}
3677
3678/*!
3679 This event handler, for event \a focusEvent, can be reimplemented in a
3680 subclass to receive focus out events.
3681
3682 The default implementation removes focus from any focus item, then removes
3683 focus from the scene.
3684
3685 \sa QGraphicsItem::focusInEvent()
3686*/
3687void QGraphicsScene::focusOutEvent(QFocusEvent *focusEvent)
3688{
3689 Q_D(QGraphicsScene);
3690 d->hasFocus = false;
3691 d->passiveFocusItem = d->focusItem;
3692 setFocusItem(nullptr, focusEvent->reason());
3693
3694 // Remove all popups when the scene loses focus.
3695 if (!d->popupWidgets.isEmpty())
3696 d->removePopup(d->popupWidgets.constFirst());
3697}
3698
3699/*!
3700 This event handler, for event \a helpEvent, can be
3701 reimplemented in a subclass to receive help events. The events
3702 are of type QEvent::ToolTip, which are created when a tooltip is
3703 requested.
3704
3705 The default implementation shows the tooltip of the topmost
3706 visible item, i.e., the item with the highest z-value, at the mouse
3707 cursor position. If no item has a tooltip set, this function
3708 does nothing.
3709
3710 Note: See items() for a definition of which items are considered visible by this function.
3711
3712 \sa QGraphicsItem::toolTip(), QGraphicsSceneHelpEvent
3713*/
3714void QGraphicsScene::helpEvent(QGraphicsSceneHelpEvent *helpEvent)
3715{
3716#if !QT_CONFIG(tooltip)
3717 Q_UNUSED(helpEvent);
3718#else
3719 // Find the first item that does tooltips
3720 Q_D(QGraphicsScene);
3721 const QList<QGraphicsItem *> itemsAtPos = d->itemsAtPosition(helpEvent->screenPos(),
3722 helpEvent->scenePos(),
3723 helpEvent->widget());
3724 QGraphicsItem *toolTipItem = nullptr;
3725 for (auto item : itemsAtPos) {
3726 if (item->d_func()->isProxyWidget()) {
3727 // if the item is a proxy widget, the event is forwarded to it
3728 sendEvent(item, helpEvent);
3729 if (helpEvent->isAccepted())
3730 return;
3731 }
3732 if (!item->toolTip().isEmpty()) {
3733 toolTipItem = item;
3734 break;
3735 }
3736 }
3737
3738 // Show or hide the tooltip
3739 QString text;
3740 QPoint point;
3741 if (toolTipItem && !toolTipItem->toolTip().isEmpty()) {
3742 text = toolTipItem->toolTip();
3743 point = helpEvent->screenPos();
3744 }
3745 QToolTip::showText(point, text, helpEvent->widget());
3746 helpEvent->setAccepted(!text.isEmpty());
3747#endif
3748}
3749
3750bool QGraphicsScenePrivate::itemAcceptsHoverEvents_helper(const QGraphicsItem *item) const
3751{
3752 return (item->d_ptr->acceptsHover
3753 || (item->d_ptr->isWidget
3754 && static_cast<const QGraphicsWidget *>(item)->d_func()->hasDecoration()))
3755 && !item->isBlockedByModalPanel();
3756}
3757
3758/*!
3759 This event handler, for event \a hoverEvent, can be reimplemented in a
3760 subclass to receive hover enter events. The default implementation
3761 forwards the event to the topmost visible item that accepts hover events at the
3762 scene position from the event.
3763
3764 Note: See items() for a definition of which items are considered visible by this function.
3765
3766 \sa QGraphicsItem::hoverEvent(), QGraphicsItem::setAcceptHoverEvents()
3767*/
3768bool QGraphicsScenePrivate::dispatchHoverEvent(QGraphicsSceneHoverEvent *hoverEvent)
3769{
3770 if (allItemsIgnoreHoverEvents)
3771 return false;
3772
3773 // Find the first item that accepts hover events, reusing earlier
3774 // calculated data is possible.
3775 if (cachedItemsUnderMouse.isEmpty()) {
3776 cachedItemsUnderMouse = itemsAtPosition(hoverEvent->screenPos(),
3777 hoverEvent->scenePos(),
3778 hoverEvent->widget());
3779 }
3780
3781 QGraphicsItem *item = nullptr;
3782 for (auto tmp : std::as_const(cachedItemsUnderMouse)) {
3783 if (itemAcceptsHoverEvents_helper(tmp)) {
3784 item = tmp;
3785 break;
3786 }
3787 }
3788
3789 // Find the common ancestor item for the new topmost hoverItem and the
3790 // last item in the hoverItem list.
3791 QGraphicsItem *commonAncestorItem = (item && !hoverItems.isEmpty()) ? item->commonAncestorItem(hoverItems.constLast()) : nullptr;
3792 while (commonAncestorItem && !itemAcceptsHoverEvents_helper(commonAncestorItem))
3793 commonAncestorItem = commonAncestorItem->parentItem();
3794 if (commonAncestorItem && commonAncestorItem->panel() != item->panel()) {
3795 // The common ancestor isn't in the same panel as the two hovered
3796 // items.
3797 commonAncestorItem = nullptr;
3798 }
3799
3800 // Check if the common ancestor item is known.
3801 int index = commonAncestorItem ? hoverItems.indexOf(commonAncestorItem) : -1;
3802 // Send hover leaves to any existing hovered children of the common
3803 // ancestor item.
3804 for (int i = hoverItems.size() - 1; i > index; --i) {
3805 QGraphicsItem *lastItem = hoverItems.takeLast();
3806 if (itemAcceptsHoverEvents_helper(lastItem))
3807 sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, hoverEvent);
3808 }
3809
3810 // Item is a child of a known item. Generate enter events for the
3811 // missing links.
3812 QList<QGraphicsItem *> parents;
3813 QGraphicsItem *parent = item;
3814 while (parent && parent != commonAncestorItem) {
3815 parents.append(parent);
3816 if (parent->isPanel()) {
3817 // Stop at the panel - we don't deliver beyond this point.
3818 break;
3819 }
3820 parent = parent->parentItem();
3821 }
3822 for (auto it = parents.crbegin(), end = parents.crend(); it != end; ++it) {
3823 QGraphicsItem *parent = *it;
3824 hoverItems << parent;
3825 if (itemAcceptsHoverEvents_helper(parent))
3826 sendHoverEvent(QEvent::GraphicsSceneHoverEnter, parent, hoverEvent);
3827 }
3828
3829 // Generate a move event for the item itself
3830 if (item
3831 && !hoverItems.isEmpty()
3832 && item == hoverItems.constLast()) {
3833 sendHoverEvent(QEvent::GraphicsSceneHoverMove, item, hoverEvent);
3834 return true;
3835 }
3836 return false;
3837}
3838
3839/*!
3840 \internal
3841
3842 Handles all actions necessary to clean up the scene when the mouse leaves
3843 the view.
3844*/
3845void QGraphicsScenePrivate::leaveScene(QWidget *viewport)
3846{
3847#if QT_CONFIG(tooltip)
3848 QToolTip::hideText();
3849#endif
3850 QGraphicsView *view = qobject_cast<QGraphicsView *>(viewport->parent());
3851 // Send HoverLeave events to all existing hover items, topmost first.
3852 QGraphicsSceneHoverEvent hoverEvent;
3853 hoverEvent.setWidget(viewport);
3854
3855 if (view) {
3856 QPoint cursorPos = QCursor::pos();
3857 hoverEvent.setScenePos(view->mapToScene(viewport->mapFromGlobal(cursorPos)));
3858 hoverEvent.setLastScenePos(hoverEvent.scenePos());
3859 hoverEvent.setScreenPos(cursorPos);
3860 hoverEvent.setLastScreenPos(hoverEvent.screenPos());
3861 }
3862
3863 while (!hoverItems.isEmpty()) {
3864 QGraphicsItem *lastItem = hoverItems.takeLast();
3865 if (itemAcceptsHoverEvents_helper(lastItem))
3866 sendHoverEvent(QEvent::GraphicsSceneHoverLeave, lastItem, &hoverEvent);
3867 }
3868}
3869
3870/*!
3871 This event handler, for event \a keyEvent, can be reimplemented in a
3872 subclass to receive keypress events. The default implementation forwards
3873 the event to current focus item.
3874
3875 \sa QGraphicsItem::keyPressEvent(), focusItem()
3876*/
3877void QGraphicsScene::keyPressEvent(QKeyEvent *keyEvent)
3878{
3879 // ### Merge this function with keyReleaseEvent; they are identical
3880 // ### (except this comment).
3881 Q_D(QGraphicsScene);
3882 QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.constLast() : 0;
3883 if (!item)
3884 item = focusItem();
3885 if (item) {
3886 QGraphicsItem *p = item;
3887 do {
3888 // Accept the event by default
3889 keyEvent->accept();
3890 // Send it; QGraphicsItem::keyPressEvent ignores it. If the event
3891 // is filtered out, stop propagating it.
3892 if (p->isBlockedByModalPanel())
3893 break;
3894 if (!d->sendEvent(p, keyEvent))
3895 break;
3896 } while (!keyEvent->isAccepted() && !p->isPanel() && (p = p->parentItem()));
3897 } else {
3898 keyEvent->ignore();
3899 }
3900}
3901
3902/*!
3903 This event handler, for event \a keyEvent, can be reimplemented in a
3904 subclass to receive key release events. The default implementation
3905 forwards the event to current focus item.
3906
3907 \sa QGraphicsItem::keyReleaseEvent(), focusItem()
3908*/
3909void QGraphicsScene::keyReleaseEvent(QKeyEvent *keyEvent)
3910{
3911 // ### Merge this function with keyPressEvent; they are identical (except
3912 // ### this comment).
3913 Q_D(QGraphicsScene);
3914 QGraphicsItem *item = !d->keyboardGrabberItems.isEmpty() ? d->keyboardGrabberItems.constLast() : 0;
3915 if (!item)
3916 item = focusItem();
3917 if (item) {
3918 QGraphicsItem *p = item;
3919 do {
3920 // Accept the event by default
3921 keyEvent->accept();
3922 // Send it; QGraphicsItem::keyPressEvent ignores it. If the event
3923 // is filtered out, stop propagating it.
3924 if (p->isBlockedByModalPanel())
3925 break;
3926 if (!d->sendEvent(p, keyEvent))
3927 break;
3928 } while (!keyEvent->isAccepted() && !p->isPanel() && (p = p->parentItem()));
3929 } else {
3930 keyEvent->ignore();
3931 }
3932}
3933
3934/*!
3935 This event handler, for event \a mouseEvent, can be reimplemented
3936 in a subclass to receive mouse press events for the scene.
3937
3938 The default implementation depends on the state of the scene. If
3939 there is a mouse grabber item, then the event is sent to the mouse
3940 grabber. Otherwise, it is forwarded to the topmost visible item that
3941 accepts mouse events at the scene position from the event, and
3942 that item promptly becomes the mouse grabber item.
3943
3944 If there is no item at the given position on the scene, the
3945 selection area is reset, any focus item loses its input focus, and
3946 the event is then ignored.
3947
3948 Note: See items() for a definition of which items are considered visible by this function.
3949
3950 \sa QGraphicsItem::mousePressEvent(),
3951 QGraphicsItem::setAcceptedMouseButtons()
3952*/
3953void QGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
3954{
3955 Q_D(QGraphicsScene);
3956 if (d->mouseGrabberItems.isEmpty()) {
3957 // Dispatch hover events
3958 QGraphicsSceneHoverEvent hover;
3959 _q_hoverFromMouseEvent(&hover, mouseEvent);
3960 d->dispatchHoverEvent(&hover);
3961 }
3962
3963 d->mousePressEventHandler(mouseEvent);
3964}
3965
3966/*!
3967 This event handler, for event \a mouseEvent, can be reimplemented
3968 in a subclass to receive mouse move events for the scene.
3969
3970 The default implementation depends on the mouse grabber state. If there is
3971 a mouse grabber item, the event is sent to the mouse grabber. If there
3972 are any items that accept hover events at the current position, the event
3973 is translated into a hover event and accepted; otherwise it's ignored.
3974
3975 \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseReleaseEvent(),
3976 QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
3977*/
3978void QGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
3979{
3980 Q_D(QGraphicsScene);
3981 if (d->mouseGrabberItems.isEmpty()) {
3982 if (mouseEvent->buttons())
3983 return;
3984 QGraphicsSceneHoverEvent hover;
3985 _q_hoverFromMouseEvent(&hover, mouseEvent);
3986 mouseEvent->setAccepted(d->dispatchHoverEvent(&hover));
3987 return;
3988 }
3989
3990 // Forward the event to the mouse grabber
3991 d->sendMouseEvent(mouseEvent);
3992 mouseEvent->accept();
3993}
3994
3995/*!
3996 This event handler, for event \a mouseEvent, can be reimplemented
3997 in a subclass to receive mouse release events for the scene.
3998
3999 The default implementation depends on the mouse grabber state. If
4000 there is no mouse grabber, the event is ignored. Otherwise, if
4001 there is a mouse grabber item, the event is sent to the mouse
4002 grabber. If this mouse release represents the last pressed button
4003 on the mouse, the mouse grabber item then loses the mouse grab.
4004
4005 \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
4006 QGraphicsItem::mouseDoubleClickEvent(), QGraphicsItem::setAcceptedMouseButtons()
4007*/
4008void QGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
4009{
4010 Q_D(QGraphicsScene);
4011 if (d->mouseGrabberItems.isEmpty()) {
4012 mouseEvent->ignore();
4013 return;
4014 }
4015
4016 // Forward the event to the mouse grabber
4017 d->sendMouseEvent(mouseEvent);
4018 mouseEvent->accept();
4019
4020 // Reset the mouse grabber when the last mouse button has been released.
4021 if (!mouseEvent->buttons()) {
4022 if (!d->mouseGrabberItems.isEmpty()) {
4023 d->lastMouseGrabberItem = d->mouseGrabberItems.constLast();
4024 if (d->lastMouseGrabberItemHasImplicitMouseGrab)
4025 d->mouseGrabberItems.constLast()->ungrabMouse();
4026 } else {
4027 d->lastMouseGrabberItem = nullptr;
4028 }
4029
4030 // Generate a hoverevent
4031 QGraphicsSceneHoverEvent hoverEvent;
4032 _q_hoverFromMouseEvent(&hoverEvent, mouseEvent);
4033 d->dispatchHoverEvent(&hoverEvent);
4034 }
4035}
4036
4037/*!
4038 This event handler, for event \a mouseEvent, can be reimplemented
4039 in a subclass to receive mouse double-click events for the scene.
4040
4041 If someone doubleclicks on the scene, the scene will first receive
4042 a mouse press event, followed by a release event (i.e., a click),
4043 then a double-click event, and finally a release event. If the
4044 double-click event is delivered to a different item than the one
4045 that received the first press and release, it will be delivered as
4046 a press event. However, tripleclick events are not delivered as
4047 double-click events in this case.
4048
4049 The default implementation is similar to mousePressEvent().
4050
4051 Note: See items() for a definition of which items are considered visible by this function.
4052
4053 \sa QGraphicsItem::mousePressEvent(), QGraphicsItem::mouseMoveEvent(),
4054 QGraphicsItem::mouseReleaseEvent(), QGraphicsItem::setAcceptedMouseButtons()
4055*/
4056void QGraphicsScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent)
4057{
4058 Q_D(QGraphicsScene);
4059 d->mousePressEventHandler(mouseEvent);
4060}
4061
4062/*!
4063 This event handler, for event \a wheelEvent, can be reimplemented in a
4064 subclass to receive mouse wheel events for the scene.
4065
4066 By default, the event is delivered to the topmost visible item under the
4067 cursor. If ignored, the event propagates to the item beneath, and again
4068 until the event is accepted, or it reaches the scene. If no items accept
4069 the event, it is ignored.
4070
4071 Note: See items() for a definition of which items are considered visible by this function.
4072
4073 \sa QGraphicsItem::wheelEvent()
4074*/
4075void QGraphicsScene::wheelEvent(QGraphicsSceneWheelEvent *wheelEvent)
4076{
4077 Q_D(QGraphicsScene);
4078 const QList<QGraphicsItem *> wheelCandidates = d->itemsAtPosition(wheelEvent->screenPos(),
4079 wheelEvent->scenePos(),
4080 wheelEvent->widget());
4081
4082 // Find the first popup under the mouse (including the popup's descendants) starting from the last.
4083 // Remove all popups after the one found, or all or them if no popup is under the mouse.
4084 // Then continue with the event.
4085 QList<QGraphicsWidget *>::const_iterator iter = d->popupWidgets.constEnd();
4086 while (iter > d->popupWidgets.constBegin() && !wheelCandidates.isEmpty()) {
4087 --iter;
4088 if (wheelCandidates.first() == *iter || (*iter)->isAncestorOf(wheelCandidates.first()))
4089 break;
4090 d->removePopup(*iter);
4091 }
4092
4093 bool hasSetFocus = false;
4094 for (QGraphicsItem *item : wheelCandidates) {
4095 if (!hasSetFocus && item->isEnabled()
4096 && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) {
4097 if (item->isWidget() && static_cast<QGraphicsWidget *>(item)->focusPolicy() == Qt::WheelFocus) {
4098 hasSetFocus = true;
4099 if (item != focusItem())
4100 setFocusItem(item, Qt::MouseFocusReason);
4101 }
4102 }
4103
4104 wheelEvent->setPos(item->d_ptr->genericMapFromScene(wheelEvent->scenePos(),
4105 wheelEvent->widget()));
4106 wheelEvent->accept();
4107 bool isPanel = item->isPanel();
4108 bool ret = d->sendEvent(item, wheelEvent);
4109
4110 if (ret && (isPanel || wheelEvent->isAccepted()))
4111 break;
4112 }
4113}
4114
4115/*!
4116 This event handler, for event \a event, can be reimplemented in a
4117 subclass to receive input method events for the scene.
4118
4119 The default implementation forwards the event to the focusItem().
4120 If no item currently has focus or the current focus item does not
4121 accept input methods, this function does nothing.
4122
4123 \sa QGraphicsItem::inputMethodEvent()
4124*/
4125void QGraphicsScene::inputMethodEvent(QInputMethodEvent *event)
4126{
4127 Q_D(QGraphicsScene);
4128 if (d->focusItem && (d->focusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod)) {
4129 d->sendEvent(d->focusItem, event);
4130 return;
4131 }
4132 if (d->lastFocusItem && d->lastFocusItem != d->focusItem && (d->lastFocusItem->flags() & QGraphicsItem::ItemAcceptsInputMethod))
4133 d->sendEvent(d->lastFocusItem, event);
4134}
4135
4136/*!
4137 Draws the background of the scene using \a painter, before any items and
4138 the foreground are drawn. Reimplement this function to provide a custom
4139 background for the scene.
4140
4141 All painting is done in \e scene coordinates. The \a rect
4142 parameter is the exposed rectangle.
4143
4144 If all you want is to define a color, texture, or gradient for the
4145 background, you can call setBackgroundBrush() instead.
4146
4147 \sa drawForeground(), drawItems()
4148*/
4149void QGraphicsScene::drawBackground(QPainter *painter, const QRectF &rect)
4150{
4151 Q_D(QGraphicsScene);
4152
4153 if (d->backgroundBrush.style() != Qt::NoBrush) {
4154 if (d->painterStateProtection)
4155 painter->save();
4156 painter->setBrushOrigin(0, 0);
4157 painter->fillRect(rect, backgroundBrush());
4158 if (d->painterStateProtection)
4159 painter->restore();
4160 }
4161}
4162
4163/*!
4164 Draws the foreground of the scene using \a painter, after the background
4165 and all items have been drawn. Reimplement this function to provide a
4166 custom foreground for the scene.
4167
4168 All painting is done in \e scene coordinates. The \a rect
4169 parameter is the exposed rectangle.
4170
4171 If all you want is to define a color, texture or gradient for the
4172 foreground, you can call setForegroundBrush() instead.
4173
4174 \sa drawBackground(), drawItems()
4175*/
4176void QGraphicsScene::drawForeground(QPainter *painter, const QRectF &rect)
4177{
4178 Q_D(QGraphicsScene);
4179
4180 if (d->foregroundBrush.style() != Qt::NoBrush) {
4181 if (d->painterStateProtection)
4182 painter->save();
4183 painter->setBrushOrigin(0, 0);
4184 painter->fillRect(rect, foregroundBrush());
4185 if (d->painterStateProtection)
4186 painter->restore();
4187 }
4188}
4189
4190static void _q_paintItem(QGraphicsItem *item, QPainter *painter,
4191 const QStyleOptionGraphicsItem *option, QWidget *widget,
4192 bool useWindowOpacity, bool painterStateProtection)
4193{
4194 if (!item->isWidget()) {
4195 item->paint(painter, option, widget);
4196 return;
4197 }
4198 QGraphicsWidget *widgetItem = static_cast<QGraphicsWidget *>(item);
4199 QGraphicsProxyWidget *proxy = qobject_cast<QGraphicsProxyWidget *>(widgetItem);
4200 const qreal windowOpacity = (proxy && proxy->widget() && useWindowOpacity)
4201 ? proxy->widget()->windowOpacity() : 1.0;
4202 const qreal oldPainterOpacity = painter->opacity();
4203
4204 if (qFuzzyIsNull(windowOpacity))
4205 return;
4206 // Set new painter opacity.
4207 if (windowOpacity < 1.0)
4208 painter->setOpacity(oldPainterOpacity * windowOpacity);
4209
4210 // set layoutdirection on the painter
4211 Qt::LayoutDirection oldLayoutDirection = painter->layoutDirection();
4212 painter->setLayoutDirection(widgetItem->layoutDirection());
4213
4214 if (widgetItem->isWindow() && widgetItem->windowType() != Qt::Popup && widgetItem->windowType() != Qt::ToolTip
4215 && !(widgetItem->windowFlags() & Qt::FramelessWindowHint)) {
4216 if (painterStateProtection)
4217 painter->save();
4218 widgetItem->paintWindowFrame(painter, option, widget);
4219 if (painterStateProtection)
4220 painter->restore();
4221 } else if (widgetItem->autoFillBackground()) {
4222 painter->fillRect(option->exposedRect, widgetItem->palette().window());
4223 }
4224
4225 widgetItem->paint(painter, option, widget);
4226
4227 // Restore layoutdirection on the painter.
4228 painter->setLayoutDirection(oldLayoutDirection);
4229 // Restore painter opacity.
4230 if (windowOpacity < 1.0)
4231 painter->setOpacity(oldPainterOpacity);
4232}
4233
4234static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed,
4235 const QTransform &itemToPixmap, QPainter::RenderHints renderHints,
4236 const QStyleOptionGraphicsItem *option, bool painterStateProtection)
4237{
4238 QPixmap subPix;
4239 QPainter pixmapPainter;
4240 QRect br = pixmapExposed.boundingRect();
4241
4242 // Don't use subpixmap if we get a full update.
4243 if (pixmapExposed.isEmpty() || (pixmapExposed.rectCount() == 1 && br.contains(pix->rect()))) {
4244 pix->fill(Qt::transparent);
4245 pixmapPainter.begin(pix);
4246 } else {
4247 subPix = QPixmap(br.size() * pix->devicePixelRatio());
4248 subPix.setDevicePixelRatio(pix->devicePixelRatio());
4249 subPix.fill(Qt::transparent);
4250 pixmapPainter.begin(&subPix);
4251 pixmapPainter.translate(-br.topLeft());
4252 if (!pixmapExposed.isEmpty()) {
4253 // Applied to subPix; paint is adjusted to the coordinate space is
4254 // correct.
4255 pixmapPainter.setClipRegion(pixmapExposed);
4256 }
4257 }
4258
4259 pixmapPainter.setRenderHints(pixmapPainter.renderHints(), false);
4260 pixmapPainter.setRenderHints(renderHints, true);
4261 pixmapPainter.setWorldTransform(itemToPixmap, true);
4262
4263 // Render.
4264 _q_paintItem(item, &pixmapPainter, option, nullptr, false, painterStateProtection);
4265 pixmapPainter.end();
4266
4267 if (!subPix.isNull()) {
4268 // Blit the subpixmap into the main pixmap.
4269 pixmapPainter.begin(pix);
4270 pixmapPainter.setCompositionMode(QPainter::CompositionMode_Source);
4271 pixmapPainter.setClipRegion(pixmapExposed);
4272 pixmapPainter.drawPixmap(br.topLeft(), subPix);
4273 pixmapPainter.end();
4274 }
4275}
4276
4277// Copied from qpaintengine_vg.cpp
4278// Returns \c true for 90, 180, and 270 degree rotations.
4279static inline bool transformIsSimple(const QTransform& transform)
4280{
4281 QTransform::TransformationType type = transform.type();
4282 if (type <= QTransform::TxScale) {
4283 return true;
4284 } else if (type == QTransform::TxRotate) {
4285 // Check for 90, and 270 degree rotations.
4286 qreal m11 = transform.m11();
4287 qreal m12 = transform.m12();
4288 qreal m21 = transform.m21();
4289 qreal m22 = transform.m22();
4290 if (m11 == 0.0f && m22 == 0.0f) {
4291 if (m12 == 1.0f && m21 == -1.0f)
4292 return true; // 90 degrees.
4293 else if (m12 == -1.0f && m21 == 1.0f)
4294 return true; // 270 degrees.
4295 else if (m12 == -1.0f && m21 == -1.0f)
4296 return true; // 90 degrees inverted y.
4297 else if (m12 == 1.0f && m21 == 1.0f)
4298 return true; // 270 degrees inverted y.
4299 }
4300 }
4301 return false;
4302}
4303
4304/*!
4305 \internal
4306
4307 Draws items directly, or using cache.
4308*/
4309void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painter,
4310 const QStyleOptionGraphicsItem *option, QWidget *widget,
4311 bool painterStateProtection)
4312{
4313 QGraphicsItemPrivate *itemd = item->d_ptr.data();
4314 QGraphicsItem::CacheMode cacheMode = QGraphicsItem::CacheMode(itemd->cacheMode);
4315
4316 // Render directly, using no cache.
4317 if (cacheMode == QGraphicsItem::NoCache) {
4318 _q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget, true, painterStateProtection);
4319 return;
4320 }
4321
4322 const qreal devicePixelRatio = painter->device()->devicePixelRatio();
4323 const qreal oldPainterOpacity = painter->opacity();
4324 qreal newPainterOpacity = oldPainterOpacity;
4325 QGraphicsProxyWidget *proxy = item->isWidget() ? qobject_cast<QGraphicsProxyWidget *>(static_cast<QGraphicsWidget *>(item)) : 0;
4326 if (proxy && proxy->widget()) {
4327 const qreal windowOpacity = proxy->widget()->windowOpacity();
4328 if (windowOpacity < 1.0)
4329 newPainterOpacity *= windowOpacity;
4330 }
4331
4332 // Item's (local) bounding rect
4333 QRectF brect = item->boundingRect();
4334 QRectF adjustedBrect(brect);
4335 _q_adjustRect(&adjustedBrect);
4336 if (adjustedBrect.isEmpty())
4337 return;
4338
4339 // Fetch the off-screen transparent buffer and exposed area info.
4340 QPixmapCache::Key pixmapKey;
4341 QPixmap pix;
4342
4343 bool pixmapFound;
4344 QGraphicsItemCache *itemCache = itemd->extraItemCache();
4345 if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
4346 pixmapKey = itemCache->key;
4347 } else {
4348 pixmapKey = itemCache->deviceData.value(widget).key;
4349 }
4350
4351 // Find pixmap in cache.
4352 pixmapFound = QPixmapCache::find(pixmapKey, &pix);
4353
4354 // Render using item coordinate cache mode.
4355 if (cacheMode == QGraphicsItem::ItemCoordinateCache) {
4356 QSize pixmapSize;
4357 bool fixedCacheSize = itemCache->fixedSize.isValid();
4358 QRect br = brect.toAlignedRect();
4359 if (fixedCacheSize) {
4360 pixmapSize = itemCache->fixedSize;
4361 } else {
4362 pixmapSize = br.size();
4363 }
4364
4365 pixmapSize *= devicePixelRatio;
4366
4367 // Create or recreate the pixmap.
4368 int adjust = itemCache->fixedSize.isValid() ? 0 : 2;
4369 QSize adjustSize(adjust*2, adjust*2);
4370 br.adjust(-adjust / devicePixelRatio, -adjust / devicePixelRatio, adjust / devicePixelRatio, adjust / devicePixelRatio);
4371 if (pix.isNull() || (!fixedCacheSize && (pixmapSize + adjustSize) != pix.size())) {
4372 pix = QPixmap(pixmapSize + adjustSize);
4373 itemCache->boundingRect = br;
4374 itemCache->exposed.clear();
4375 itemCache->allExposed = true;
4376 } else if (itemCache->boundingRect != br) {
4377 itemCache->boundingRect = br;
4378 itemCache->exposed.clear();
4379 itemCache->allExposed = true;
4380 }
4381
4382 // Redraw any newly exposed areas.
4383 if (itemCache->allExposed || !itemCache->exposed.isEmpty()) {
4384
4385 //We know that we will modify the pixmap, removing it from the cache
4386 //will detach the one we have and avoid a deep copy
4387 if (pixmapFound)
4388 QPixmapCache::remove(pixmapKey);
4389
4390 // Fit the item's bounding rect into the pixmap's coordinates.
4391 QTransform itemToPixmap;
4392 if (fixedCacheSize) {
4393 const QPointF scale((pixmapSize.width() / devicePixelRatio) / brect.width(),
4394 (pixmapSize.height() / devicePixelRatio) / brect.height());
4395 itemToPixmap.scale(scale.x(), scale.y());
4396 }
4397 itemToPixmap.translate(-br.x(), -br.y());
4398
4399 // Generate the item's exposedRect and map its list of expose
4400 // rects to device coordinates.
4401 styleOptionTmp = *option;
4402 QRegion pixmapExposed;
4403 QRectF exposedRect;
4404 if (!itemCache->allExposed) {
4405 for (const auto &rect : std::as_const(itemCache->exposed)) {
4406 exposedRect |= rect;
4407 pixmapExposed += itemToPixmap.mapRect(rect).toAlignedRect();
4408 }
4409 } else {
4410 exposedRect = brect;
4411 }
4412 styleOptionTmp.exposedRect = exposedRect;
4413
4414 // Render.
4415 pix.setDevicePixelRatio(devicePixelRatio);
4416 _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
4417 &styleOptionTmp, painterStateProtection);
4418
4419 // insert this pixmap into the cache.
4420 itemCache->key = QPixmapCache::insert(pix);
4421
4422 // Reset expose data.
4423 itemCache->allExposed = false;
4424 itemCache->exposed.clear();
4425 }
4426
4427 // Redraw the exposed area using the transformed painter. Depending on
4428 // the hardware, this may be a server-side operation, or an expensive
4429 // qpixmap-image-transform-pixmap roundtrip.
4430 if (newPainterOpacity != oldPainterOpacity) {
4431 painter->setOpacity(newPainterOpacity);
4432 painter->drawPixmap(br.topLeft(), pix);
4433 painter->setOpacity(oldPainterOpacity);
4434 } else {
4435 painter->drawPixmap(br.topLeft(), pix);
4436 }
4437 return;
4438 }
4439
4440 // Render using device coordinate cache mode.
4441 if (cacheMode == QGraphicsItem::DeviceCoordinateCache) {
4442 // Find the item's bounds in device coordinates.
4443 QRectF deviceBounds = painter->worldTransform().mapRect(brect);
4444 QRect deviceRect = deviceBounds.toRect().adjusted(-1, -1, 1, 1);
4445 if (deviceRect.isEmpty())
4446 return;
4447 QRect viewRect = widget ? widget->rect() : QRect();
4448 if (widget && !viewRect.intersects(deviceRect))
4449 return;
4450
4451 // Resort to direct rendering if the device rect exceeds the
4452 // (optional) maximum bounds. (QGraphicsSvgItem uses this).
4453 QSize maximumCacheSize =
4454 itemd->extra(QGraphicsItemPrivate::ExtraMaxDeviceCoordCacheSize).toSize();
4455 if (!maximumCacheSize.isEmpty()
4456 && (deviceRect.width() > maximumCacheSize.width()
4457 || deviceRect.height() > maximumCacheSize.height())) {
4458 _q_paintItem(static_cast<QGraphicsWidget *>(item), painter, option, widget,
4459 oldPainterOpacity != newPainterOpacity, painterStateProtection);
4460 return;
4461 }
4462
4463 // Create or reuse offscreen pixmap, possibly scroll/blit from the old one.
4464 // If the world transform is rotated we always recreate the cache to avoid
4465 // wrong blending.
4466 bool pixModified = false;
4467 QGraphicsItemCache::DeviceData *deviceData = &itemCache->deviceData[widget];
4468 bool invertable = true;
4469 QTransform diff = deviceData->lastTransform.inverted(&invertable);
4470 if (invertable)
4471 diff *= painter->worldTransform();
4472 deviceData->lastTransform = painter->worldTransform();
4473 bool allowPartialCacheExposure = false;
4474 bool simpleTransform = invertable && diff.type() <= QTransform::TxTranslate
4475 && transformIsSimple(painter->worldTransform());
4476 if (!simpleTransform) {
4477 pixModified = true;
4478 itemCache->allExposed = true;
4479 itemCache->exposed.clear();
4480 deviceData->cacheIndent = QPoint();
4481 pix = QPixmap();
4482 } else if (!viewRect.isNull()) {
4483 allowPartialCacheExposure = deviceData->cacheIndent != QPoint();
4484 }
4485
4486 // Allow partial cache exposure if the device rect isn't fully contained and
4487 // deviceRect is 20% taller or wider than the viewRect.
4488 if (!allowPartialCacheExposure && !viewRect.isNull() && !viewRect.contains(deviceRect)) {
4489 allowPartialCacheExposure = (viewRect.width() * 1.2 < deviceRect.width())
4490 || (viewRect.height() * 1.2 < deviceRect.height());
4491 }
4492
4493 QRegion scrollExposure;
4494 if (allowPartialCacheExposure) {
4495 // Part of pixmap is drawn. Either device contains viewrect (big
4496 // item covers whole screen) or parts of device are outside the
4497 // viewport. In either case the device rect must be the intersect
4498 // between the two.
4499 int dx = deviceRect.left() < viewRect.left() ? viewRect.left() - deviceRect.left() : 0;
4500 int dy = deviceRect.top() < viewRect.top() ? viewRect.top() - deviceRect.top() : 0;
4501 QPoint newCacheIndent(dx, dy);
4502 deviceRect &= viewRect;
4503
4504 if (pix.isNull()) {
4505 deviceData->cacheIndent = QPoint();
4506 itemCache->allExposed = true;
4507 itemCache->exposed.clear();
4508 pixModified = true;
4509 }
4510
4511 // Copy / "scroll" the old pixmap onto the new ole and calculate
4512 // scrolled exposure.
4513 if (newCacheIndent != deviceData->cacheIndent || deviceRect.size() != pix.size() / devicePixelRatio) {
4514 QPoint diff = newCacheIndent - deviceData->cacheIndent;
4515 QPixmap newPix(deviceRect.size() * devicePixelRatio);
4516 // ### Investigate removing this fill (test with Plasma and
4517 // graphicssystem raster).
4518 newPix.fill(Qt::transparent);
4519 if (!pix.isNull()) {
4520 newPix.setDevicePixelRatio(devicePixelRatio);
4521 QPainter newPixPainter(&newPix);
4522 newPixPainter.drawPixmap(-diff, pix);
4523 newPixPainter.end();
4524 }
4525 QRegion exposed;
4526 exposed += QRect(QPoint(0,0), newPix.size() / devicePixelRatio);
4527 if (!pix.isNull())
4528 exposed -= QRect(-diff, pix.size() / devicePixelRatio);
4529 scrollExposure = exposed;
4530
4531 pix = newPix;
4532 pixModified = true;
4533 }
4534 deviceData->cacheIndent = newCacheIndent;
4535 } else {
4536 // Full pixmap is drawn.
4537 deviceData->cacheIndent = QPoint();
4538
4539 // Auto-adjust the pixmap size.
4540 if (deviceRect.size() != pix.size() / devicePixelRatio) {
4541 // exposed needs to cover the whole pixmap
4542 pix = QPixmap(deviceRect.size() * devicePixelRatio);
4543 pixModified = true;
4544 itemCache->allExposed = true;
4545 itemCache->exposed.clear();
4546 }
4547 }
4548
4549 // Check for newly invalidated areas.
4550 if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) {
4551 //We know that we will modify the pixmap, removing it from the cache
4552 //will detach the one we have and avoid a deep copy
4553 if (pixmapFound)
4554 QPixmapCache::remove(pixmapKey);
4555
4556 // Construct an item-to-pixmap transform.
4557 QPointF p = deviceRect.topLeft();
4558 QTransform itemToPixmap = painter->worldTransform();
4559 if (!p.isNull())
4560 itemToPixmap *= QTransform::fromTranslate(-p.x(), -p.y());
4561
4562 // Map the item's logical expose to pixmap coordinates.
4563 QRegion pixmapExposed = scrollExposure;
4564 if (!itemCache->allExposed) {
4565 for (const auto &rect : std::as_const(itemCache->exposed))
4566 pixmapExposed += itemToPixmap.mapRect(rect).toRect().adjusted(-1, -1, 1, 1);
4567 }
4568
4569 // Calculate the style option's exposedRect.
4570 QRectF br;
4571 if (itemCache->allExposed) {
4572 br = item->boundingRect();
4573 } else {
4574 for (const auto &rect : std::as_const(itemCache->exposed))
4575 br |= rect;
4576 QTransform pixmapToItem = itemToPixmap.inverted();
4577 for (const QRect &r : std::as_const(scrollExposure))
4578 br |= pixmapToItem.mapRect(r);
4579 }
4580 styleOptionTmp = *option;
4581 styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1);
4582
4583 // Render the exposed areas.
4584 pix.setDevicePixelRatio(devicePixelRatio);
4585 _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(),
4586 &styleOptionTmp, painterStateProtection);
4587
4588 // Reset expose data.
4589 pixModified = true;
4590 itemCache->allExposed = false;
4591 itemCache->exposed.clear();
4592 }
4593
4594 if (pixModified) {
4595 // Insert this pixmap into the cache.
4596 deviceData->key = QPixmapCache::insert(pix);
4597 }
4598
4599 // Redraw the exposed area using an untransformed painter. This
4600 // effectively becomes a bitblit that does not transform the cache.
4601 QTransform restoreTransform = painter->worldTransform();
4602 painter->setWorldTransform(QTransform());
4603 if (newPainterOpacity != oldPainterOpacity) {
4604 painter->setOpacity(newPainterOpacity);
4605 painter->drawPixmap(deviceRect.topLeft(), pix);
4606 painter->setOpacity(oldPainterOpacity);
4607 } else {
4608 painter->drawPixmap(deviceRect.topLeft(), pix);
4609 }
4610 painter->setWorldTransform(restoreTransform);
4611 return;
4612 }
4613}
4614
4615void QGraphicsScenePrivate::drawItems(QPainter *painter, const QTransform *const viewTransform,
4616 QRegion *exposedRegion, QWidget *widget)
4617{
4618 // Make sure we don't have unpolished items before we draw.
4619 if (!unpolishedItems.isEmpty())
4620 _q_polishItems();
4621
4622 updateAll = false;
4623 QRectF exposedSceneRect;
4624 if (exposedRegion && indexMethod != QGraphicsScene::NoIndex) {
4625 exposedSceneRect = exposedRegion->boundingRect().adjusted(-1, -1, 1, 1);
4626 if (viewTransform)
4627 exposedSceneRect = viewTransform->inverted().mapRect(exposedSceneRect);
4628 }
4629 const QList<QGraphicsItem *> tli = index->estimateTopLevelItems(exposedSceneRect, Qt::AscendingOrder);
4630 for (const auto subTree : tli)
4631 drawSubtreeRecursive(subTree, painter, viewTransform, exposedRegion, widget);
4632}
4633
4634void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter,
4635 const QTransform *const viewTransform,
4636 QRegion *exposedRegion, QWidget *widget,
4637 qreal parentOpacity, const QTransform *const effectTransform)
4638{
4639 Q_ASSERT(item);
4640
4641 if (!item->d_ptr->visible)
4642 return;
4643
4644 const bool itemHasContents = !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
4645 const bool itemHasChildren = !item->d_ptr->children.isEmpty();
4646 if (!itemHasContents && !itemHasChildren)
4647 return; // Item has neither contents nor children!(?)
4648
4649 const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
4650 const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
4651 if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity()))
4652 return;
4653
4654 QTransform transform(Qt::Uninitialized);
4655 QTransform *transformPtr = nullptr;
4656 bool translateOnlyTransform = false;
4657#define ENSURE_TRANSFORM_PTR
4658 if (!transformPtr) {
4659 Q_ASSERT(!itemIsUntransformable);
4660 if (viewTransform) {
4661 transform = item->d_ptr->sceneTransform;
4662 transform *= *viewTransform;
4663 transformPtr = &transform;
4664 } else {
4665 transformPtr = &item->d_ptr->sceneTransform;
4666 translateOnlyTransform = item->d_ptr->sceneTransformTranslateOnly;
4667 }
4668 }
4669
4670 // Update the item's scene transform if the item is transformable;
4671 // otherwise calculate the full transform,
4672 bool wasDirtyParentSceneTransform = false;
4673 const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
4674 if (itemIsUntransformable) {
4675 transform = item->deviceTransform(viewTransform ? *viewTransform : QTransform());
4676 transformPtr = &transform;
4677 } else if (item->d_ptr->dirtySceneTransform) {
4678 item->d_ptr->updateSceneTransformFromParent();
4679 Q_ASSERT(!item->d_ptr->dirtySceneTransform);
4680 wasDirtyParentSceneTransform = true;
4681 }
4682
4683 const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape
4684 || item->d_ptr->flags & QGraphicsItem::ItemContainsChildrenInShape);
4685 bool drawItem = itemHasContents && !itemIsFullyTransparent;
4686 if (drawItem || minimumRenderSize > 0.0) {
4687 const QRectF brect = adjustedItemEffectiveBoundingRect(item);
4689 QRectF preciseViewBoundingRect = translateOnlyTransform ? brect.translated(transformPtr->dx(), transformPtr->dy())
4690 : transformPtr->mapRect(brect);
4691
4692 bool itemIsTooSmallToRender = false;
4693 if (minimumRenderSize > 0.0
4694 && (preciseViewBoundingRect.width() < minimumRenderSize
4695 || preciseViewBoundingRect.height() < minimumRenderSize)) {
4696 itemIsTooSmallToRender = true;
4697 drawItem = false;
4698 }
4699
4700 bool itemIsOutsideVisibleRect = false;
4701 if (drawItem) {
4702 QRect viewBoundingRect = preciseViewBoundingRect.toAlignedRect();
4703 viewBoundingRect.adjust(-int(rectAdjust), -int(rectAdjust), rectAdjust, rectAdjust);
4704 if (widget)
4705 item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect);
4706 drawItem = exposedRegion ? exposedRegion->intersects(viewBoundingRect)
4707 : !viewBoundingRect.normalized().isEmpty();
4708 itemIsOutsideVisibleRect = !drawItem;
4709 }
4710
4711 if (itemIsTooSmallToRender || itemIsOutsideVisibleRect) {
4712 // We cannot simply use !drawItem here. If we did it is possible
4713 // to enter the outer if statement with drawItem == false and minimumRenderSize > 0
4714 // and finally end up inside this inner if, even though none of the above two
4715 // conditions are met. In that case we should not return from this function
4716 // but call draw() instead.
4717 if (!itemHasChildren)
4718 return;
4719 if (itemClipsChildrenToShape) {
4720 if (wasDirtyParentSceneTransform)
4721 item->d_ptr->invalidateChildrenSceneTransform();
4722 return;
4723 }
4724 }
4725 } // else we know for sure this item has children we must process.
4726
4727 if (itemHasChildren && itemClipsChildrenToShape)
4729
4730#if QT_CONFIG(graphicseffect)
4731 if (item->d_ptr->graphicsEffect && item->d_ptr->graphicsEffect->isEnabled()) {
4732 ENSURE_TRANSFORM_PTR;
4733 QGraphicsItemPaintInfo info(viewTransform, transformPtr, effectTransform, exposedRegion, widget, &styleOptionTmp,
4734 painter, opacity, wasDirtyParentSceneTransform, itemHasContents && !itemIsFullyTransparent);
4735 QGraphicsEffectSource *source = item->d_ptr->graphicsEffect->d_func()->source;
4736 QGraphicsItemEffectSourcePrivate *sourced = static_cast<QGraphicsItemEffectSourcePrivate *>
4737 (source->d_func());
4738 sourced->info = &info;
4739 const QTransform restoreTransform = painter->worldTransform();
4740 if (effectTransform)
4741 painter->setWorldTransform(*transformPtr * *effectTransform);
4742 else
4743 painter->setWorldTransform(*transformPtr);
4744 painter->setOpacity(opacity);
4745
4746 if (sourced->currentCachedSystem() != Qt::LogicalCoordinates
4747 && sourced->lastEffectTransform != painter->worldTransform())
4748 {
4749 if (sourced->lastEffectTransform.type() <= QTransform::TxTranslate
4750 && painter->worldTransform().type() <= QTransform::TxTranslate)
4751 {
4752 QRectF sourceRect = sourced->boundingRect(Qt::DeviceCoordinates);
4753 QRect effectRect = sourced->paddedEffectRect(Qt::DeviceCoordinates, sourced->currentCachedMode(), sourceRect).toAlignedRect();
4754
4755 sourced->setCachedOffset(effectRect.topLeft());
4756 } else {
4757 sourced->invalidateCache(QGraphicsEffectSourcePrivate::TransformChanged);
4758 }
4759
4760 sourced->lastEffectTransform = painter->worldTransform();
4761 }
4762
4763 item->d_ptr->graphicsEffect->draw(painter);
4764 painter->setWorldTransform(restoreTransform);
4765 sourced->info = nullptr;
4766 } else
4767#endif // QT_CONFIG(graphicseffect)
4768 {
4769 draw(item, painter, viewTransform, transformPtr, exposedRegion, widget, opacity,
4770 effectTransform, wasDirtyParentSceneTransform, drawItem);
4771 }
4772}
4773
4774static inline void setClip(QPainter *painter, QGraphicsItem *item)
4775{
4776 painter->save();
4777 QRectF clipRect;
4778 const QPainterPath clipPath(item->shape());
4779 if (QPathClipper::pathToRect(clipPath, &clipRect))
4780 painter->setClipRect(clipRect.normalized(), Qt::IntersectClip);
4781 else
4782 painter->setClipPath(clipPath, Qt::IntersectClip);
4783}
4784
4785static inline void setWorldTransform(QPainter *painter, const QTransform *const transformPtr,
4786 const QTransform *effectTransform)
4787{
4788 Q_ASSERT(transformPtr);
4789 if (effectTransform)
4790 painter->setWorldTransform(*transformPtr * *effectTransform);
4791 else
4792 painter->setWorldTransform(*transformPtr);
4793}
4794
4795void QGraphicsScenePrivate::draw(QGraphicsItem *item, QPainter *painter, const QTransform *const viewTransform,
4796 const QTransform *const transformPtr, QRegion *exposedRegion, QWidget *widget,
4797 qreal opacity, const QTransform *effectTransform,
4798 bool wasDirtyParentSceneTransform, bool drawItem)
4799{
4800 const auto &children = item->d_ptr->children;
4801
4802 const bool itemIsFullyTransparent = QGraphicsItemPrivate::isOpacityNull(opacity);
4803 const bool itemClipsChildrenToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape);
4804 const bool itemHasChildren = !children.isEmpty();
4805 bool setChildClip = itemClipsChildrenToShape;
4806 bool itemHasChildrenStackedBehind = false;
4807
4808 int i = 0;
4809 if (itemHasChildren) {
4810 if (itemClipsChildrenToShape)
4811 setWorldTransform(painter, transformPtr, effectTransform);
4812
4813 item->d_ptr->ensureSortedChildren();
4814 // Items with the 'ItemStacksBehindParent' flag are put in front of the list
4815 // so all we have to do is to check the first item.
4816 itemHasChildrenStackedBehind = (children.at(0)->d_ptr->flags
4817 & QGraphicsItem::ItemStacksBehindParent);
4818
4819 if (itemHasChildrenStackedBehind) {
4820 if (itemClipsChildrenToShape) {
4821 setClip(painter, item);
4822 setChildClip = false;
4823 }
4824
4825 // Draw children behind
4826 for (i = 0; i < children.size(); ++i) {
4827 QGraphicsItem *child = children.at(i);
4828 if (wasDirtyParentSceneTransform)
4829 child->d_ptr->dirtySceneTransform = 1;
4830 if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent))
4831 break;
4832 if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
4833 continue;
4834 drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, opacity, effectTransform);
4835 }
4836 }
4837 }
4838
4839 // Draw item
4840 if (drawItem) {
4841 Q_ASSERT(!itemIsFullyTransparent);
4842 Q_ASSERT(!(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents));
4843 Q_ASSERT(transformPtr);
4844 item->d_ptr->initStyleOption(&styleOptionTmp, *transformPtr, exposedRegion
4845 ? *exposedRegion : QRegion(), exposedRegion == nullptr);
4846
4847 const bool itemClipsToShape = item->d_ptr->flags & QGraphicsItem::ItemClipsToShape;
4848 bool restorePainterClip = false;
4849
4850 if (!itemHasChildren || !itemClipsChildrenToShape) {
4851 // Item does not have children or clip children to shape.
4852 setWorldTransform(painter, transformPtr, effectTransform);
4853 if ((restorePainterClip = itemClipsToShape))
4854 setClip(painter, item);
4855 } else if (itemHasChildrenStackedBehind){
4856 // Item clips children to shape and has children stacked behind, which means
4857 // the painter is already clipped to the item's shape.
4858 if (itemClipsToShape) {
4859 // The clip is already correct. Ensure correct world transform.
4860 setWorldTransform(painter, transformPtr, effectTransform);
4861 } else {
4862 // Remove clip (this also ensures correct world transform).
4863 painter->restore();
4864 setChildClip = true;
4865 }
4866 } else if (itemClipsToShape) {
4867 // Item clips children and itself to shape. It does not have hildren stacked
4868 // behind, which means the clip has not yet been set. We set it now and re-use it
4869 // for the children.
4870 setClip(painter, item);
4871 setChildClip = false;
4872 }
4873
4874 if (painterStateProtection && !restorePainterClip)
4875 painter->save();
4876
4877 painter->setOpacity(opacity);
4878 if (!item->d_ptr->cacheMode && !item->d_ptr->isWidget)
4879 item->paint(painter, &styleOptionTmp, widget);
4880 else
4881 drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection);
4882
4883 if (painterStateProtection || restorePainterClip)
4884 painter->restore();
4885
4886 static int drawRect = qEnvironmentVariableIntValue("QT_DRAW_SCENE_ITEM_RECTS");
4887 if (drawRect) {
4888 QPen oldPen = painter->pen();
4889 QBrush oldBrush = painter->brush();
4890 quintptr ptr = reinterpret_cast<quintptr>(item);
4891 const QColor color = QColor::fromHsv(ptr % 255, 255, 255);
4892 painter->setPen(color);
4893 painter->setBrush(Qt::NoBrush);
4894 painter->drawRect(adjustedItemBoundingRect(item));
4895 painter->setPen(oldPen);
4896 painter->setBrush(oldBrush);
4897 }
4898 }
4899
4900 // Draw children in front
4901 if (itemHasChildren) {
4902 if (setChildClip)
4903 setClip(painter, item);
4904
4905 for (; i < children.size(); ++i) {
4906 QGraphicsItem *child = children.at(i);
4907 if (wasDirtyParentSceneTransform)
4908 child->d_ptr->dirtySceneTransform = 1;
4909 if (itemIsFullyTransparent && !(child->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity))
4910 continue;
4911 drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, opacity, effectTransform);
4912 }
4913
4914 // Restore child clip
4915 if (itemClipsChildrenToShape)
4916 painter->restore();
4917 }
4918}
4919
4920void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren,
4921 bool force, bool ignoreOpacity, bool removingItemFromScene,
4922 bool updateBoundingRect)
4923{
4924 Q_ASSERT(item);
4925 if (updateAll)
4926 return;
4927
4928 if (removingItemFromScene && !ignoreOpacity && !item->d_ptr->ignoreOpacity) {
4929 // If any of the item's ancestors ignore opacity, it means that the opacity
4930 // was set to 0 (and the update request has not yet been processed). That
4931 // also means that we have to ignore the opacity for the item itself; otherwise
4932 // things like: parent->setOpacity(0); scene->removeItem(child) won't work.
4933 // Note that we only do this when removing items from the scene. In all other
4934 // cases the ignoreOpacity bit propagates properly in processDirtyItems, but
4935 // since the item is removed immediately it won't be processed there.
4936 QGraphicsItem *p = item->d_ptr->parent;
4937 while (p) {
4938 if (p->d_ptr->ignoreOpacity) {
4939 item->d_ptr->ignoreOpacity = true;
4940 break;
4941 }
4942 p = p->d_ptr->parent;
4943 }
4944 }
4945
4946 if (item->d_ptr->discardUpdateRequest(/*ignoreVisibleBit=*/force,
4947 /*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren,
4948 /*ignoreOpacity=*/ignoreOpacity)) {
4949 if (item->d_ptr->dirty) {
4950 // The item is already marked as dirty and will be processed later. However,
4951 // we have to make sure ignoreVisible and ignoreOpacity are set properly;
4952 // otherwise things like: item->update(); item->hide() (force is now true)
4953 // won't work as expected.
4954 if (force)
4955 item->d_ptr->ignoreVisible = 1;
4956 if (ignoreOpacity)
4957 item->d_ptr->ignoreOpacity = 1;
4958 }
4959 return;
4960 }
4961
4962 const bool fullItemUpdate = rect.isNull();
4963 if (!fullItemUpdate && rect.isEmpty())
4964 return;
4965
4966 if (!processDirtyItemsEmitted) {
4967 QMetaMethod method = q_ptr->metaObject()->method(processDirtyItemsIndex);
4968 method.invoke(q_ptr, Qt::QueuedConnection);
4969// QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection);
4970 processDirtyItemsEmitted = true;
4971 }
4972
4973 if (removingItemFromScene) {
4974 // Note that this function can be called from the item's destructor, so
4975 // do NOT call any virtual functions on it within this block.
4976 if (isSignalConnected(changedSignalIndex) || views.isEmpty()) {
4977 // This block of code is kept for compatibility. Since 4.5, by default
4978 // QGraphicsView does not connect the signal and we use the below
4979 // method of delivering updates.
4980 q_func()->update();
4981 return;
4982 }
4983
4984 for (auto view : std::as_const(views)) {
4985 QGraphicsViewPrivate *viewPrivate = view->d_func();
4986 QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport);
4987 rect.translate(viewPrivate->dirtyScrollOffset);
4988 viewPrivate->updateRect(rect);
4989 }
4990 return;
4991 }
4992
4993 bool hasNoContents = item->d_ptr->flags & QGraphicsItem::ItemHasNoContents;
4994 if (!hasNoContents) {
4995 item->d_ptr->dirty = 1;
4996 if (fullItemUpdate)
4997 item->d_ptr->fullUpdatePending = 1;
4998 else if (!item->d_ptr->fullUpdatePending)
4999 item->d_ptr->needsRepaint |= rect;
5000 } else if (item->d_ptr->graphicsEffect) {
5001 invalidateChildren = true;
5002 }
5003
5004 if (invalidateChildren) {
5005 item->d_ptr->allChildrenDirty = 1;
5006 item->d_ptr->dirtyChildren = 1;
5007 }
5008
5009 if (force)
5010 item->d_ptr->ignoreVisible = 1;
5011 if (ignoreOpacity)
5012 item->d_ptr->ignoreOpacity = 1;
5013
5014 if (!updateBoundingRect)
5015 item->d_ptr->markParentDirty();
5016}
5017
5018static inline bool updateHelper(QGraphicsViewPrivate *view, QGraphicsItemPrivate *item,
5019 const QRectF &rect, bool itemIsUntransformable)
5020{
5021 Q_ASSERT(view);
5022 Q_ASSERT(item);
5023
5024 QGraphicsItem *itemq = static_cast<QGraphicsItem *>(item->q_ptr);
5025 QGraphicsView *viewq = static_cast<QGraphicsView *>(view->q_ptr);
5026
5027 if (itemIsUntransformable) {
5028 const QTransform xform = itemq->deviceTransform(viewq->viewportTransform());
5029 if (!item->hasBoundingRegionGranularity)
5030 return view->updateRectF(xform.mapRect(rect));
5031 return view->updateRegion(rect, xform);
5032 }
5033
5034 if (item->sceneTransformTranslateOnly && view->identityMatrix) {
5035 const qreal dx = item->sceneTransform.dx();
5036 const qreal dy = item->sceneTransform.dy();
5037 QRectF r(rect);
5038 r.translate(dx - view->horizontalScroll(), dy - view->verticalScroll());
5039 return view->updateRectF(r);
5040 }
5041
5042 if (!viewq->isTransformed()) {
5043 if (!item->hasBoundingRegionGranularity)
5044 return view->updateRectF(item->sceneTransform.mapRect(rect));
5045 return view->updateRegion(rect, item->sceneTransform);
5046 }
5047
5048 QTransform xform = item->sceneTransform;
5049 xform *= viewq->viewportTransform();
5050 if (!item->hasBoundingRegionGranularity)
5051 return view->updateRectF(xform.mapRect(rect));
5052 return view->updateRegion(rect, xform);
5053}
5054
5055void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren,
5056 qreal parentOpacity)
5057{
5058 Q_Q(QGraphicsScene);
5059 Q_ASSERT(item);
5060 Q_ASSERT(!updateAll);
5061
5062 if (!item->d_ptr->dirty && !item->d_ptr->dirtyChildren) {
5063 resetDirtyItem(item);
5064 return;
5065 }
5066
5067 const bool itemIsHidden = !item->d_ptr->ignoreVisible && !item->d_ptr->visible;
5068 if (itemIsHidden) {
5069 resetDirtyItem(item, /*recursive=*/true);
5070 return;
5071 }
5072
5073 bool itemHasContents = !(item->d_ptr->flags & QGraphicsItem::ItemHasNoContents);
5074 const bool itemHasChildren = !item->d_ptr->children.isEmpty();
5075 if (!itemHasContents) {
5076 if (!itemHasChildren) {
5077 resetDirtyItem(item);
5078 return; // Item has neither contents nor children!(?)
5079 }
5080 if (item->d_ptr->graphicsEffect)
5081 itemHasContents = true;
5082 }
5083
5084 const qreal opacity = item->d_ptr->combineOpacityFromParent(parentOpacity);
5085 const bool itemIsFullyTransparent = !item->d_ptr->ignoreOpacity
5086 && QGraphicsItemPrivate::isOpacityNull(opacity);
5087 if (itemIsFullyTransparent && (!itemHasChildren || item->d_ptr->childrenCombineOpacity())) {
5088 resetDirtyItem(item, /*recursive=*/itemHasChildren);
5089 return;
5090 }
5091
5092 bool wasDirtyParentSceneTransform = item->d_ptr->dirtySceneTransform;
5093 const bool itemIsUntransformable = item->d_ptr->itemIsUntransformable();
5094 if (wasDirtyParentSceneTransform && !itemIsUntransformable) {
5095 item->d_ptr->updateSceneTransformFromParent();
5096 Q_ASSERT(!item->d_ptr->dirtySceneTransform);
5097 }
5098
5099 const bool wasDirtyParentViewBoundingRects = item->d_ptr->paintedViewBoundingRectsNeedRepaint;
5100 if (itemIsFullyTransparent || !itemHasContents || dirtyAncestorContainsChildren) {
5101 // Make sure we don't process invisible items or items with no content.
5102 item->d_ptr->dirty = 0;
5103 item->d_ptr->fullUpdatePending = 0;
5104 // Might have a dirty view bounding rect otherwise.
5105 if (itemIsFullyTransparent || !itemHasContents)
5106 item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0;
5107 }
5108
5109 if (!hasSceneRect && item->d_ptr->geometryChanged && item->d_ptr->visible) {
5110 // Update growingItemsBoundingRect.
5111 if (item->d_ptr->sceneTransformTranslateOnly) {
5112 growingItemsBoundingRect |= item->boundingRect().translated(item->d_ptr->sceneTransform.dx(),
5113 item->d_ptr->sceneTransform.dy());
5114 } else {
5115 growingItemsBoundingRect |= item->d_ptr->sceneTransform.mapRect(item->boundingRect());
5116 }
5117 }
5118
5119 // Process item.
5120 if (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
5121 const bool useCompatUpdate = views.isEmpty() || isSignalConnected(changedSignalIndex);
5122 const QRectF itemBoundingRect = adjustedItemEffectiveBoundingRect(item);
5123
5124 if (useCompatUpdate && !itemIsUntransformable && qFuzzyIsNull(item->boundingRegionGranularity())) {
5125 // This block of code is kept for compatibility. Since 4.5, by default
5126 // QGraphicsView does not connect the signal and we use the below
5127 // method of delivering updates.
5128 if (item->d_ptr->sceneTransformTranslateOnly) {
5129 q->update(itemBoundingRect.translated(item->d_ptr->sceneTransform.dx(),
5130 item->d_ptr->sceneTransform.dy()));
5131 } else {
5132 QRectF rect = item->d_ptr->sceneTransform.mapRect(itemBoundingRect);
5133 if (!rect.isEmpty())
5134 q->update(rect);
5135 }
5136 } else {
5137 QRectF dirtyRect;
5138 bool uninitializedDirtyRect = true;
5139
5140 for (auto view : std::as_const(views)) {
5141 QGraphicsViewPrivate *viewPrivate = view->d_func();
5142 QRect &paintedViewBoundingRect = item->d_ptr->paintedViewBoundingRects[viewPrivate->viewport];
5143 if (viewPrivate->fullUpdatePending
5144 || viewPrivate->viewportUpdateMode == QGraphicsView::NoViewportUpdate) {
5145 // Okay, if we have a full update pending or no viewport update, this item's
5146 // paintedViewBoundingRect will be updated correctly in the next paintEvent if
5147 // it is inside the viewport, but for now we can pretend that it is outside.
5148 paintedViewBoundingRect = QRect(-1, -1, -1, -1);
5149 continue;
5150 }
5151
5152 if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
5153 paintedViewBoundingRect.translate(viewPrivate->dirtyScrollOffset);
5154 if (!viewPrivate->updateRect(paintedViewBoundingRect))
5155 paintedViewBoundingRect = QRect(-1, -1, -1, -1); // Outside viewport.
5156 }
5157
5158 if (!item->d_ptr->dirty)
5159 continue;
5160
5161 if (!item->d_ptr->paintedViewBoundingRectsNeedRepaint
5162 && paintedViewBoundingRect.x() == -1 && paintedViewBoundingRect.y() == -1
5163 && paintedViewBoundingRect.width() == -1 && paintedViewBoundingRect.height() == -1) {
5164 continue; // Outside viewport.
5165 }
5166
5167 if (uninitializedDirtyRect) {
5168 dirtyRect = itemBoundingRect;
5169 if (!item->d_ptr->fullUpdatePending) {
5170 _q_adjustRect(&item->d_ptr->needsRepaint);
5171 dirtyRect &= item->d_ptr->needsRepaint;
5172 }
5173 uninitializedDirtyRect = false;
5174 }
5175
5176 if (dirtyRect.isEmpty())
5177 continue; // Discard updates outside the bounding rect.
5178
5179 if (!updateHelper(viewPrivate, item->d_ptr.data(), dirtyRect, itemIsUntransformable)
5180 && item->d_ptr->paintedViewBoundingRectsNeedRepaint) {
5181 paintedViewBoundingRect = QRect(-1, -1, -1, -1); // Outside viewport.
5182 }
5183 }
5184 }
5185 }
5186
5187 // Process children.
5188 if (itemHasChildren && item->d_ptr->dirtyChildren) {
5189 const bool itemClipsChildrenToShape = item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape
5190 || item->d_ptr->flags & QGraphicsItem::ItemContainsChildrenInShape;
5191 // Items with no content are threated as 'dummy' items which means they are never drawn and
5192 // 'processed', so the painted view bounding rect is never up-to-date. This means that whenever
5193 // such an item changes geometry, its children have to take care of the update regardless
5194 // of whether the item clips children to shape or not.
5195 const bool bypassUpdateClip = !itemHasContents && wasDirtyParentViewBoundingRects;
5196 if (itemClipsChildrenToShape && !bypassUpdateClip) {
5197 // Make sure child updates are clipped to the item's bounding rect.
5198 for (auto view : std::as_const(views))
5199 view->d_func()->setUpdateClip(item);
5200 }
5201 if (!dirtyAncestorContainsChildren) {
5202 dirtyAncestorContainsChildren = item->d_ptr->fullUpdatePending
5203 && itemClipsChildrenToShape;
5204 }
5205 const bool allChildrenDirty = item->d_ptr->allChildrenDirty;
5206 const bool parentIgnoresVisible = item->d_ptr->ignoreVisible;
5207 const bool parentIgnoresOpacity = item->d_ptr->ignoreOpacity;
5208 for (auto child : std::as_const(item->d_ptr->children)) {
5209 if (wasDirtyParentSceneTransform)
5210 child->d_ptr->dirtySceneTransform = 1;
5211 if (wasDirtyParentViewBoundingRects)
5212 child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1;
5213 if (parentIgnoresVisible)
5214 child->d_ptr->ignoreVisible = 1;
5215 if (parentIgnoresOpacity)
5216 child->d_ptr->ignoreOpacity = 1;
5217 if (allChildrenDirty) {
5218 child->d_ptr->dirty = 1;
5219 child->d_ptr->fullUpdatePending = 1;
5220 child->d_ptr->dirtyChildren = 1;
5221 child->d_ptr->allChildrenDirty = 1;
5222 }
5223 processDirtyItemsRecursive(child, dirtyAncestorContainsChildren, opacity);
5224 }
5225
5226 if (itemClipsChildrenToShape) {
5227 // Reset updateClip.
5228 for (auto view : std::as_const(views))
5229 view->d_func()->setUpdateClip(nullptr);
5230 }
5231 } else if (wasDirtyParentSceneTransform) {
5232 item->d_ptr->invalidateChildrenSceneTransform();
5233 }
5234
5235 resetDirtyItem(item);
5236}
5237
5238/*!
5239 \deprecated
5240
5241 Paints the given \a items using the provided \a painter, after the
5242 background has been drawn, and before the foreground has been
5243 drawn. All painting is done in \e scene coordinates. Before
5244 drawing each item, the painter must be transformed using
5245 QGraphicsItem::sceneTransform().
5246
5247 The \a options parameter is the list of style option objects for
5248 each item in \a items. The \a numItems parameter is the number of
5249 items in \a items and options in \a options. The \a widget
5250 parameter is optional; if specified, it should point to the widget
5251 that is being painted on.
5252
5253 The default implementation prepares the painter matrix, and calls
5254 QGraphicsItem::paint() on all items. Reimplement this function to
5255 provide custom painting of all items for the scene; gaining
5256 complete control over how each item is drawn. In some cases this
5257 can increase drawing performance significantly.
5258
5259 Example:
5260
5261 \snippet graphicssceneadditem/graphicssceneadditemsnippet.cpp 0
5262
5263 Since Qt 4.6, this function is not called anymore unless
5264 the QGraphicsView::IndirectPainting flag is given as an Optimization
5265 flag.
5266
5267 \sa drawBackground(), drawForeground()
5268*/
5269void QGraphicsScene::drawItems(QPainter *painter,
5270 int numItems,
5271 QGraphicsItem *items[],
5272 const QStyleOptionGraphicsItem options[], QWidget *widget)
5273{
5274 Q_D(QGraphicsScene);
5275 // Make sure we don't have unpolished items before we draw.
5276 if (!d->unpolishedItems.isEmpty())
5277 d->_q_polishItems();
5278
5279 const qreal opacity = painter->opacity();
5280 QTransform viewTransform = painter->worldTransform();
5281 Q_UNUSED(options);
5282
5283 // Determine view, expose and flags.
5284 QGraphicsView *view = widget ? qobject_cast<QGraphicsView *>(widget->parentWidget()) : 0;
5285 QRegion *expose = nullptr;
5286 const quint32 oldRectAdjust = d->rectAdjust;
5287 if (view) {
5288 d->updateAll = false;
5289 expose = &view->d_func()->exposedRegion;
5290 if (view->d_func()->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
5291 d->rectAdjust = 1;
5292 else
5293 d->rectAdjust = 2;
5294 }
5295
5296 // Find all toplevels, they are already sorted.
5297 QList<QGraphicsItem *> topLevelItems;
5298 for (int i = 0; i < numItems; ++i) {
5299 QGraphicsItem *item = items[i]->topLevelItem();
5300 if (!item->d_ptr->itemDiscovered) {
5301 topLevelItems << item;
5302 item->d_ptr->itemDiscovered = 1;
5303 d->drawSubtreeRecursive(item, painter, &viewTransform, expose, widget);
5304 }
5305 }
5306
5307 d->rectAdjust = oldRectAdjust;
5308 // Reset discovery bits.
5309 for (auto topLevelItem : std::as_const(topLevelItems))
5310 topLevelItem->d_ptr->itemDiscovered = 0;
5311
5312 painter->setWorldTransform(viewTransform);
5313 painter->setOpacity(opacity);
5314}
5315
5316/*!
5317 \since 4.4
5318
5319 Finds a new widget to give the keyboard focus to, as appropriate for Tab
5320 and Shift+Tab, and returns \c true if it can find a new widget, or false if
5321 it cannot. If \a next is true, this function searches forward; if \a next
5322 is false, it searches backward.
5323
5324 You can reimplement this function in a subclass of QGraphicsScene to
5325 provide fine-grained control over how tab focus passes inside your
5326 scene. The default implementation is based on the tab focus chain defined
5327 by QGraphicsWidget::setTabOrder().
5328*/
5329bool QGraphicsScene::focusNextPrevChild(bool next)
5330{
5331 Q_D(QGraphicsScene);
5332
5333 QGraphicsItem *item = focusItem();
5334 if (item && !item->isWidget()) {
5335 // Tab out of the scene.
5336 return false;
5337 }
5338 if (!item) {
5339 if (d->lastFocusItem && !d->lastFocusItem->isWidget()) {
5340 // Restore focus to the last focusable non-widget item that had
5341 // focus.
5342 setFocusItem(d->lastFocusItem, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
5343 return true;
5344 }
5345 if (d->activePanel) {
5346 if (d->activePanel->flags() & QGraphicsItem::ItemIsFocusable) {
5347 setFocusItem(d->activePanel, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
5348 return true;
5349 }
5350 if (d->activePanel->isWidget()) {
5351 QGraphicsWidget *test = static_cast<QGraphicsWidget *>(d->activePanel);
5352 QGraphicsWidget *fw = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
5353 do {
5354 if (fw->focusPolicy() & Qt::TabFocus) {
5355 setFocusItem(fw, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
5356 return true;
5357 }
5358 fw = next ? fw->d_func()->focusNext : fw->d_func()->focusPrev;
5359 } while (fw != d->activePanel);
5360 }
5361 }
5362 }
5363 if (!item && !d->tabFocusFirst) {
5364 // No widgets...
5365 return false;
5366 }
5367
5368 // The item must be a widget.
5369 QGraphicsWidget *widget = nullptr;
5370 if (!item) {
5371 widget = next ? d->tabFocusFirst : d->tabFocusFirst->d_func()->focusPrev;
5372 } else {
5373 QGraphicsWidget *test = static_cast<QGraphicsWidget *>(item);
5374 widget = next ? test->d_func()->focusNext : test->d_func()->focusPrev;
5375 if (!widget->panel() && ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))) {
5376 // Tab out of the scene.
5377 return false;
5378 }
5379 }
5380 QGraphicsWidget *widgetThatHadFocus = widget;
5381
5382 // Run around the focus chain until we find a widget that can take tab focus.
5383 do {
5384 if (widget->flags() & QGraphicsItem::ItemIsFocusable
5385 && widget->isEnabled() && widget->isVisibleTo(nullptr)
5386 && (widget->focusPolicy() & Qt::TabFocus)
5387 && (!item || !item->isPanel() || item->isAncestorOf(widget))
5388 ) {
5389 setFocusItem(widget, next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
5390 return true;
5391 }
5392 widget = next ? widget->d_func()->focusNext : widget->d_func()->focusPrev;
5393 if ((next && widget == d->tabFocusFirst) || (!next && widget == d->tabFocusFirst->d_func()->focusPrev))
5394 return false;
5395 } while (widget != widgetThatHadFocus);
5396
5397 return false;
5398}
5399
5400/*!
5401 \fn QGraphicsScene::changed(const QList<QRectF> &region)
5402
5403 This signal is emitted by QGraphicsScene when control reaches the
5404 event loop, if the scene content changes. The \a region parameter
5405 contains a list of scene rectangles that indicate the area that
5406 has been changed.
5407
5408 \sa QGraphicsView::updateScene()
5409*/
5410
5411/*!
5412 \fn QGraphicsScene::sceneRectChanged(const QRectF &rect)
5413
5414 This signal is emitted by QGraphicsScene whenever the scene rect changes.
5415 The \a rect parameter is the new scene rectangle.
5416
5417 \sa QGraphicsView::updateSceneRect()
5418*/
5419
5420/*!
5421 \fn QGraphicsScene::selectionChanged()
5422 \since 4.3
5423
5424 This signal is emitted by QGraphicsScene whenever the selection
5425 changes. You can call selectedItems() to get the new list of selected
5426 items.
5427
5428 The selection changes whenever an item is selected or unselected, a
5429 selection area is set, cleared or otherwise changed, if a preselected item
5430 is added to the scene, or if a selected item is removed from the scene.
5431
5432 QGraphicsScene emits this signal only once for group selection operations.
5433 For example, if you set a selection area, select or unselect a
5434 QGraphicsItemGroup, or if you add or remove from the scene a parent item
5435 that contains several selected items, selectionChanged() is emitted only
5436 once after the operation has completed (instead of once for each item).
5437
5438 \sa setSelectionArea(), selectedItems(), QGraphicsItem::setSelected()
5439*/
5440
5441/*!
5442 \fn void QGraphicsScene::focusItemChanged(QGraphicsItem *newFocusItem, QGraphicsItem *oldFocusItem, Qt::FocusReason reason)
5443
5444 This signal is emitted by QGraphicsScene whenever focus changes in the
5445 scene (i.e., when an item gains or loses input focus, or when focus
5446 passes from one item to another). You can connect to this signal if you
5447 need to keep track of when other items gain input focus. It is
5448 particularly useful for implementing virtual keyboards, input methods,
5449 and cursor items.
5450
5451 \a oldFocusItem is a pointer to the item that previously had focus, or
5452 0 if no item had focus before the signal was emitted. \a newFocusItem
5453 is a pointer to the item that gained input focus, or \nullptr if focus was lost.
5454 \a reason is the reason for the focus change (e.g., if the scene was
5455 deactivated while an input field had focus, \a oldFocusItem would point
5456 to the input field item, \a newFocusItem would be \nullptr, and \a reason
5457 would be Qt::ActiveWindowFocusReason.
5458*/
5459
5460/*!
5461 \since 4.4
5462
5463 Returns the scene's style, or the same as QApplication::style() if the
5464 scene has not been explicitly assigned a style.
5465
5466 \sa setStyle()
5467*/
5468QStyle *QGraphicsScene::style() const
5469{
5470 Q_D(const QGraphicsScene);
5471 // ### This function, and the use of styles in general, is non-reentrant.
5472 return d->style ? d->style : QApplication::style();
5473}
5474
5475/*!
5476 \since 4.4
5477
5478 Sets or replaces the style of the scene to \a style, and reparents the
5479 style to this scene. Any previously assigned style is deleted. The scene's
5480 style defaults to QApplication::style(), and serves as the default for all
5481 QGraphicsWidget items in the scene.
5482
5483 Changing the style, either directly by calling this function, or
5484 indirectly by calling QApplication::setStyle(), will automatically update
5485 the style for all widgets in the scene that do not have a style explicitly
5486 assigned to them.
5487
5488 If \a style is \nullptr, QGraphicsScene will revert to QApplication::style().
5489
5490 \sa style()
5491*/
5492void QGraphicsScene::setStyle(QStyle *style)
5493{
5494 Q_D(QGraphicsScene);
5495 // ### This function, and the use of styles in general, is non-reentrant.
5496 if (style == d->style)
5497 return;
5498
5499 // Delete the old style,
5500 delete d->style;
5501 if ((d->style = style))
5502 d->style->setParent(this);
5503
5504 // Notify the scene.
5505 QEvent event(QEvent::StyleChange);
5506 QCoreApplication::sendEvent(this, &event);
5507
5508 // Notify all widgets that don't have a style explicitly set.
5509 const auto items_ = items();
5510 for (QGraphicsItem *item : items_) {
5511 if (item->isWidget()) {
5512 QGraphicsWidget *widget = static_cast<QGraphicsWidget *>(item);
5513 if (!widget->testAttribute(Qt::WA_SetStyle))
5514 QCoreApplication::sendEvent(widget, &event);
5515 }
5516 }
5517}
5518
5519/*!
5520 \property QGraphicsScene::font
5521 \since 4.4
5522 \brief the scene's default font
5523
5524 This property provides the scene's font. The scene font defaults to,
5525 and resolves all its entries from, QApplication::font.
5526
5527 If the scene's font changes, either directly through setFont() or
5528 indirectly when the application font changes, QGraphicsScene first
5529 sends itself a \l{QEvent::FontChange}{FontChange} event, and it then
5530 sends \l{QEvent::FontChange}{FontChange} events to all top-level
5531 widget items in the scene. These items respond by resolving their own
5532 fonts to the scene, and they then notify their children, who again
5533 notify their children, and so on, until all widget items have updated
5534 their fonts.
5535
5536 Changing the scene font, (directly or indirectly through
5537 QApplication::setFont(),) automatically schedules a redraw the entire
5538 scene.
5539
5540 \sa QWidget::font, QApplication::setFont(), palette, style()
5541*/
5542QFont QGraphicsScene::font() const
5543{
5544 Q_D(const QGraphicsScene);
5545 return d->font;
5546}
5547void QGraphicsScene::setFont(const QFont &font)
5548{
5549 Q_D(QGraphicsScene);
5550 QFont naturalFont = QApplication::font();
5551 naturalFont.setResolveMask(0);
5552 QFont resolvedFont = font.resolve(naturalFont);
5553 d->setFont_helper(resolvedFont);
5554}
5555
5556/*!
5557 \property QGraphicsScene::palette
5558 \since 4.4
5559 \brief the scene's default palette
5560
5561 This property provides the scene's palette. The scene palette defaults to,
5562 and resolves all its entries from, QApplication::palette.
5563
5564 If the scene's palette changes, either directly through setPalette() or
5565 indirectly when the application palette changes, QGraphicsScene first
5566 sends itself a \l{QEvent::PaletteChange}{PaletteChange} event, and it then
5567 sends \l{QEvent::PaletteChange}{PaletteChange} events to all top-level
5568 widget items in the scene. These items respond by resolving their own
5569 palettes to the scene, and they then notify their children, who again
5570 notify their children, and so on, until all widget items have updated
5571 their palettes.
5572
5573 Changing the scene palette, (directly or indirectly through
5574 QApplication::setPalette(),) automatically schedules a redraw the entire
5575 scene.
5576
5577 \sa QWidget::palette, QApplication::setPalette(), font, style()
5578*/
5579QPalette QGraphicsScene::palette() const
5580{
5581 Q_D(const QGraphicsScene);
5582 return d->palette;
5583}
5584void QGraphicsScene::setPalette(const QPalette &palette)
5585{
5586 Q_D(QGraphicsScene);
5587 QPalette naturalPalette = QGuiApplication::palette();
5588 naturalPalette.setResolveMask(0);
5589 QPalette resolvedPalette = palette.resolve(naturalPalette);
5590 d->setPalette_helper(resolvedPalette);
5591}
5592
5593/*!
5594 \since 4.6
5595
5596 Returns \c true if the scene is active (e.g., it's viewed by
5597 at least one QGraphicsView that is active); otherwise returns \c false.
5598
5599 \sa QGraphicsItem::isActive(), QWidget::isActiveWindow()
5600*/
5601bool QGraphicsScene::isActive() const
5602{
5603 Q_D(const QGraphicsScene);
5604 return d->activationRefCount > 0;
5605}
5606
5607/*!
5608 \since 4.6
5609 Returns the current active panel, or \nullptr if no panel is
5610 currently active.
5611
5612 \sa QGraphicsScene::setActivePanel()
5613*/
5614QGraphicsItem *QGraphicsScene::activePanel() const
5615{
5616 Q_D(const QGraphicsScene);
5617 return d->activePanel;
5618}
5619
5620/*!
5621 \since 4.6
5622 Activates \a item, which must be an item in this scene. You
5623 can also pass 0 for \a item, in which case QGraphicsScene will
5624 deactivate any currently active panel.
5625
5626 If the scene is currently inactive, \a item remains inactive until the
5627 scene becomes active (or, ir \a item is \nullptr, no item will be activated).
5628
5629 \sa activePanel(), isActive(), QGraphicsItem::isActive()
5630*/
5631void QGraphicsScene::setActivePanel(QGraphicsItem *item)
5632{
5633 Q_D(QGraphicsScene);
5634 d->setActivePanelHelper(item, false);
5635}
5636
5637/*!
5638 \since 4.4
5639
5640 Returns the current active window, or \nullptr if no window is
5641 currently active.
5642
5643 \sa QGraphicsScene::setActiveWindow()
5644*/
5645QGraphicsWidget *QGraphicsScene::activeWindow() const
5646{
5647 Q_D(const QGraphicsScene);
5648 if (d->activePanel && d->activePanel->isWindow())
5649 return static_cast<QGraphicsWidget *>(d->activePanel);
5650 return nullptr;
5651}
5652
5653/*!
5654 \since 4.4
5655 Activates \a widget, which must be a widget in this scene. You can also
5656 pass 0 for \a widget, in which case QGraphicsScene will deactivate any
5657 currently active window.
5658
5659 \sa activeWindow(), QGraphicsWidget::isActiveWindow()
5660*/
5661void QGraphicsScene::setActiveWindow(QGraphicsWidget *widget)
5662{
5663 if (widget && widget->scene() != this) {
5664 qWarning("QGraphicsScene::setActiveWindow: widget %p must be part of this scene",
5665 widget);
5666 return;
5667 }
5668
5669 // Activate the widget's panel (all windows are panels).
5670 QGraphicsItem *panel = widget ? widget->panel() : nullptr;
5671 setActivePanel(panel);
5672
5673 // Raise
5674 if (panel) {
5675 QGraphicsItem *parent = panel->parentItem();
5676 // Raise ### inefficient for toplevels
5677
5678 // Find the highest z value.
5679 qreal z = panel->zValue();
5680 const auto siblings = parent ? parent->childItems() : items();
5681 for (QGraphicsItem *sibling : siblings) {
5682 if (sibling != panel && sibling->isWindow())
5683 z = qMax(z, sibling->zValue());
5684 }
5685
5686 // This will probably never overflow.
5687 const qreal litt = qreal(0.001);
5688 panel->setZValue(z + litt);
5689 }
5690}
5691
5692/*!
5693 \since 4.6
5694
5695 Sends event \a event to item \a item through possible event filters.
5696
5697 The event is sent only if the item is enabled.
5698
5699 Returns \c false if the event was filtered or if the item is disabled.
5700 Otherwise returns the value that was returned from the event handler.
5701
5702 \sa QGraphicsItem::sceneEvent(), QGraphicsItem::sceneEventFilter()
5703*/
5704bool QGraphicsScene::sendEvent(QGraphicsItem *item, QEvent *event)
5705{
5706 Q_D(QGraphicsScene);
5707 if (!item) {
5708 qWarning("QGraphicsScene::sendEvent: cannot send event to a null item");
5709 return false;
5710 }
5711 if (item->scene() != this) {
5712 qWarning("QGraphicsScene::sendEvent: item %p's scene (%p)"
5713 " is different from this scene (%p)",
5714 item, item->scene(), this);
5715 return false;
5716 }
5717 return d->sendEvent(item, event);
5718}
5719
5720/*!
5721 \property QGraphicsScene::minimumRenderSize
5722 \since 5.4
5723 \brief the minimal view-transformed size an item must have to be drawn
5724
5725 When the scene is rendered, any item whose width or height, transformed
5726 to the target view, is smaller that minimumRenderSize(), will not be
5727 rendered. If an item is not rendered and it clips its children items
5728 they will also not be rendered. Set this value to speed up rendering
5729 of scenes with many objects rendered on a zoomed out view.
5730
5731 The default value is 0. If unset, or if set to 0 or a negative value,
5732 all items will always be rendered.
5733
5734 For example, setting this property can be especially useful if a scene
5735 is rendered by multiple views, one of which serves as an overview which
5736 always displays all items. In scenes with many items, such a view will
5737 use a high scaling factor so that all items can be shown. Due to the
5738 scaling, smaller items will only make an insignificant contribution to
5739 the final rendered scene. To avoid drawing these items and reduce the
5740 time necessary to render the scene, you can call setMinimumRenderSize()
5741 with a non-negative value.
5742
5743 \note Items that are not drawn as a result of being too small, are still
5744 returned by methods such as items() and itemAt(), and participate in
5745 collision detection and interactions. It is recommended that you set
5746 minimumRenderSize() to a value less than or equal to 1 in order to
5747 avoid large unrendered items that are interactive.
5748
5749 \sa QStyleOptionGraphicsItem::levelOfDetailFromTransform()
5750*/
5751qreal QGraphicsScene::minimumRenderSize() const
5752{
5753 Q_D(const QGraphicsScene);
5754 return d->minimumRenderSize;
5755}
5756void QGraphicsScene::setMinimumRenderSize(qreal minSize)
5757{
5758 Q_D(QGraphicsScene);
5759 d->minimumRenderSize = minSize;
5760 update();
5761}
5762
5763/*!
5764 \property QGraphicsScene::focusOnTouch
5765 \since 5.12
5766 \brief whether items gain focus when receiving a \e {touch begin} event.
5767
5768 The usual behavior is to transfer focus only when an item is clicked. Often
5769 a tap on a touchpad is interpreted as equivalent to a mouse click by the
5770 operating system, generating a synthesized click event in response. However,
5771 at least on macOS you can configure this behavior.
5772
5773 By default, QGraphicsScene also transfers focus when you touch on a trackpad
5774 or similar. If the operating system is configured to not generate a
5775 synthetic mouse click on tapping the trackpad, this is surprising. If the
5776 operating system does generate synthetic mouse clicks on tapping the
5777 trackpad, the focus transfer on starting a touch gesture is unnecessary.
5778
5779 With focusOnTouch switched off, QGraphicsScene behaves as one would expect
5780 on macOS.
5781
5782 The default value is \c true, ensuring that the default behavior is just as
5783 in Qt versions prior to 5.12. Set to \c false to prevent touch events from
5784 triggering focus changes.
5785*/
5786bool QGraphicsScene::focusOnTouch() const
5787{
5788 Q_D(const QGraphicsScene);
5789 return d->focusOnTouch;
5790}
5791
5792void QGraphicsScene::setFocusOnTouch(bool enabled)
5793{
5794 Q_D(QGraphicsScene);
5795 d->focusOnTouch = enabled;
5796}
5797
5798void QGraphicsScenePrivate::addView(QGraphicsView *view)
5799{
5800 views << view;
5801#ifndef QT_NO_GESTURES
5802 for (auto it = grabbedGestures.constBegin();
5803 it != grabbedGestures.constEnd(); ++it)
5804 view->viewport()->grabGesture(it.key());
5805#endif
5806}
5807
5808void QGraphicsScenePrivate::removeView(QGraphicsView *view)
5809{
5810 views.removeAll(view);
5811}
5812
5813void QGraphicsScenePrivate::updateTouchPointsForItem(QGraphicsItem *item, QTouchEvent *touchEvent)
5814{
5815 const QTransform mapFromScene =
5816 item->d_ptr->genericMapFromSceneTransform(static_cast<const QWidget *>(touchEvent->target()));
5817
5818 for (int i = 0; i < touchEvent->pointCount(); ++i) {
5819 auto &pt = touchEvent->point(i);
5820 QMutableEventPoint::setPosition(pt, mapFromScene.map(pt.scenePosition()));
5821 }
5822}
5823
5824int QGraphicsScenePrivate::findClosestTouchPointId(const QPointF &scenePos)
5825{
5826 int closestTouchPointId = -1;
5827 qreal closestDistance = qreal(0.);
5828 for (const QEventPoint &touchPoint : std::as_const(sceneCurrentTouchPoints)) {
5829 qreal distance = QLineF(scenePos, touchPoint.scenePosition()).length();
5830 if (closestTouchPointId == -1|| distance < closestDistance) {
5831 closestTouchPointId = touchPoint.id();
5832 closestDistance = distance;
5833 }
5834 }
5835 return closestTouchPointId;
5836}
5837
5838void QGraphicsScenePrivate::touchEventHandler(QTouchEvent *sceneTouchEvent)
5839{
5840 typedef std::pair<QEventPoint::States, QList<QEventPoint> > StatesAndTouchPoints;
5841 QHash<QGraphicsItem *, StatesAndTouchPoints> itemsNeedingEvents;
5842
5843 const auto &touchPoints = sceneTouchEvent->points();
5844 for (const auto &touchPoint : touchPoints) {
5845 // update state
5846 QGraphicsItem *item = nullptr;
5847 if (touchPoint.state() == QEventPoint::State::Pressed) {
5848 if (sceneTouchEvent->pointingDevice()->type() == QInputDevice::DeviceType::TouchPad) {
5849 // on touch-pad devices, send all touch points to the same item
5850 item = itemForTouchPointId.isEmpty()
5851 ? 0
5852 : itemForTouchPointId.constBegin().value();
5853 }
5854
5855 if (!item) {
5856 // determine which item this touch point will go to
5857 cachedItemsUnderMouse = itemsAtPosition(touchPoint.globalPosition().toPoint(),
5858 touchPoint.scenePosition(),
5859 static_cast<QWidget *>(sceneTouchEvent->target()));
5860 item = cachedItemsUnderMouse.isEmpty() ? 0 : cachedItemsUnderMouse.constFirst();
5861 }
5862
5863 if (sceneTouchEvent->pointingDevice()->type() == QInputDevice::DeviceType::TouchScreen) {
5864 // on touch-screens, combine this touch point with the closest one we find
5865 int closestTouchPointId = findClosestTouchPointId(touchPoint.scenePosition());
5866 QGraphicsItem *closestItem = itemForTouchPointId.value(closestTouchPointId);
5867 if (!item || (closestItem && cachedItemsUnderMouse.contains(closestItem)))
5868 item = closestItem;
5869 }
5870 if (!item)
5871 continue;
5872
5873 itemForTouchPointId.insert(touchPoint.id(), item);
5874 sceneCurrentTouchPoints.insert(touchPoint.id(), touchPoint);
5875 } else if (touchPoint.state() == QEventPoint::State::Released) {
5876 item = itemForTouchPointId.take(touchPoint.id());
5877 if (!item)
5878 continue;
5879
5880 sceneCurrentTouchPoints.remove(touchPoint.id());
5881 } else {
5882 item = itemForTouchPointId.value(touchPoint.id());
5883 if (!item)
5884 continue;
5885 Q_ASSERT(sceneCurrentTouchPoints.contains(touchPoint.id()));
5886 sceneCurrentTouchPoints[touchPoint.id()] = touchPoint;
5887 }
5888
5889 StatesAndTouchPoints &statesAndTouchPoints = itemsNeedingEvents[item];
5890 statesAndTouchPoints.first = QEventPoint::States(statesAndTouchPoints.first | touchPoint.state());
5891 statesAndTouchPoints.second.append(touchPoint);
5892 }
5893
5894 if (itemsNeedingEvents.isEmpty()) {
5895 sceneTouchEvent->ignore();
5896 return;
5897 }
5898
5899 bool ignoreSceneTouchEvent = true;
5900 QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator it = itemsNeedingEvents.constBegin();
5901 const QHash<QGraphicsItem *, StatesAndTouchPoints>::ConstIterator end = itemsNeedingEvents.constEnd();
5902 for (; it != end; ++it) {
5903 QGraphicsItem *item = it.key();
5904
5905 (void) item->isBlockedByModalPanel(&item);
5906
5907 // determine event type from the state mask
5908 QEvent::Type eventType;
5909 switch (it.value().first) {
5910 case QEventPoint::State::Pressed:
5911 // all touch points have pressed state
5912 eventType = QEvent::TouchBegin;
5913 break;
5914 case QEventPoint::State::Released:
5915 // all touch points have released state
5916 eventType = QEvent::TouchEnd;
5917 break;
5918 case QEventPoint::State::Stationary:
5919 // don't send the event if nothing changed
5920 continue;
5921 default:
5922 // all other combinations
5923 eventType = QEvent::TouchUpdate;
5924 break;
5925 }
5926
5927 QMutableTouchEvent touchEvent(eventType, sceneTouchEvent->pointingDevice(), sceneTouchEvent->modifiers(), it.value().second);
5928 touchEvent.setTarget(sceneTouchEvent->target());
5929 touchEvent.setModifiers(sceneTouchEvent->modifiers());
5930 touchEvent.setTimestamp(sceneTouchEvent->timestamp());
5931
5932 switch (touchEvent.type()) {
5933 case QEvent::TouchBegin:
5934 {
5935 // if the TouchBegin handler recurses, we assume that means the event
5936 // has been implicitly accepted and continue to send touch events
5937 item->d_ptr->acceptedTouchBeginEvent = true;
5938 bool res = sendTouchBeginEvent(item, &touchEvent) && touchEvent.isAccepted();
5939 if (!res) {
5940 // forget about these touch points, we didn't handle them
5941 const auto &unhandledTouchPoints = touchEvent.points();
5942 for (const auto &touchPoint : unhandledTouchPoints) {
5943 itemForTouchPointId.remove(touchPoint.id());
5944 sceneCurrentTouchPoints.remove(touchPoint.id());
5945 }
5946 ignoreSceneTouchEvent = false;
5947 }
5948 break;
5949 }
5950 default:
5951 if (item->d_ptr->acceptedTouchBeginEvent) {
5952 updateTouchPointsForItem(item, &touchEvent);
5953 (void) sendEvent(item, &touchEvent);
5954 ignoreSceneTouchEvent = false;
5955 }
5956 break;
5957 }
5958 }
5959 // don't override the acceptance state of the individual points
5960 sceneTouchEvent->QInputEvent::setAccepted(ignoreSceneTouchEvent);
5961}
5962
5963bool QGraphicsScenePrivate::sendTouchBeginEvent(QGraphicsItem *origin, QTouchEvent *touchEvent)
5964{
5965 Q_Q(QGraphicsScene);
5966
5967 if (focusOnTouch) {
5968 if (cachedItemsUnderMouse.isEmpty() || cachedItemsUnderMouse.constFirst() != origin) {
5969 const QEventPoint &firstTouchPoint = touchEvent->points().first();
5970 cachedItemsUnderMouse = itemsAtPosition(firstTouchPoint.globalPosition().toPoint(),
5971 firstTouchPoint.scenePosition(),
5972 static_cast<QWidget *>(touchEvent->target()));
5973 }
5974
5975 // Set focus on the topmost enabled item that can take focus.
5976 bool setFocus = false;
5977
5978 for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
5979 if (item->isEnabled() && ((item->flags() & QGraphicsItem::ItemIsFocusable) && item->d_ptr->mouseSetsFocus)) {
5980 if (!item->isWidget() || ((QGraphicsWidget *)item)->focusPolicy() & Qt::ClickFocus) {
5981 setFocus = true;
5982 if (item != q->focusItem())
5983 q->setFocusItem(item, Qt::MouseFocusReason);
5984 break;
5985 }
5986 }
5987 if (item->isPanel())
5988 break;
5989 if (item->d_ptr->flags & QGraphicsItem::ItemStopsClickFocusPropagation)
5990 break;
5991 if (item->d_ptr->flags & QGraphicsItem::ItemStopsFocusHandling) {
5992 // Make sure we don't clear focus.
5993 setFocus = true;
5994 break;
5995 }
5996 }
5997
5998 // If nobody could take focus, clear it.
5999 if (!stickyFocus && !setFocus)
6000 q->setFocusItem(nullptr, Qt::MouseFocusReason);
6001 }
6002
6003 bool res = false;
6004 bool eventAccepted = touchEvent->isAccepted();
6005 for (QGraphicsItem *item : std::as_const(cachedItemsUnderMouse)) {
6006 // first, try to deliver the touch event
6007 updateTouchPointsForItem(item, touchEvent);
6008 bool acceptTouchEvents = item->acceptTouchEvents();
6009 touchEvent->setAccepted(acceptTouchEvents);
6010 res = acceptTouchEvents && sendEvent(item, touchEvent);
6011 eventAccepted = touchEvent->isAccepted();
6012 if (itemForTouchPointId.value(touchEvent->points().first().id()) == 0) {
6013 // item was deleted
6014 item = nullptr;
6015 } else {
6016 item->d_ptr->acceptedTouchBeginEvent = (res && eventAccepted);
6017 }
6018 touchEvent->m_spont = false;
6019 if (res && eventAccepted) {
6020 // the first item to accept the TouchBegin gets an implicit grab.
6021 const auto &touchPoints = touchEvent->points();
6022 for (const auto &touchPoint : touchPoints)
6023 itemForTouchPointId[touchPoint.id()] = item; // can be zero
6024 break;
6025 }
6026 if (item && item->isPanel())
6027 break;
6028 }
6029
6030 // don't override the acceptance state of the touch points
6031 touchEvent->QInputEvent::setAccepted(eventAccepted);
6032 return res;
6033}
6034
6035void QGraphicsScenePrivate::enableTouchEventsOnViews()
6036{
6037 for (QGraphicsView *view : std::as_const(views))
6038 view->viewport()->setAttribute(Qt::WA_AcceptTouchEvents, true);
6039}
6040
6041void QGraphicsScenePrivate::updateInputMethodSensitivityInViews()
6042{
6043 for (auto view : std::as_const(views))
6044 view->d_func()->updateInputMethodSensitivity();
6045}
6046
6047void QGraphicsScenePrivate::enterModal(QGraphicsItem *panel, QGraphicsItem::PanelModality previousModality)
6048{
6049 Q_Q(QGraphicsScene);
6050 Q_ASSERT(panel && panel->isPanel());
6051
6052 QGraphicsItem::PanelModality panelModality = panel->d_ptr->panelModality;
6053 if (previousModality != QGraphicsItem::NonModal) {
6054 // the panel is changing from one modality type to another... temporarily set it back so
6055 // that blockedPanels is populated correctly
6056 panel->d_ptr->panelModality = previousModality;
6057 }
6058
6059 QSet<QGraphicsItem *> blockedPanels;
6060 {
6061 const auto items_ = q->items();
6062 for (const auto &item : items_) {
6063 if (item->isPanel() && item->isBlockedByModalPanel())
6064 blockedPanels.insert(item);
6065 }
6066 }
6067 // blockedPanels contains all currently blocked panels
6068
6069 if (previousModality != QGraphicsItem::NonModal) {
6070 // reset the modality to the proper value, since we changed it above
6071 panel->d_ptr->panelModality = panelModality;
6072 // remove this panel so that it will be reinserted at the front of the stack
6073 modalPanels.removeAll(panel);
6074 }
6075
6076 modalPanels.prepend(panel);
6077
6078 if (!hoverItems.isEmpty()) {
6079 // send GraphicsSceneHoverLeave events to newly blocked hoverItems
6080 QGraphicsSceneHoverEvent hoverEvent;
6081 hoverEvent.setScenePos(lastSceneMousePos);
6082 dispatchHoverEvent(&hoverEvent);
6083 }
6084
6085 if (!mouseGrabberItems.isEmpty() && lastMouseGrabberItemHasImplicitMouseGrab) {
6086 QGraphicsItem *item = mouseGrabberItems.constLast();
6087 if (item->isBlockedByModalPanel())
6088 ungrabMouse(item, /*itemIsDying =*/ false);
6089 }
6090
6091 QEvent windowBlockedEvent(QEvent::WindowBlocked);
6092 QEvent windowUnblockedEvent(QEvent::WindowUnblocked);
6093 const auto items_ = q->items();
6094 for (const auto &item : items_) {
6095 if (item->isPanel()) {
6096 if (!blockedPanels.contains(item) && item->isBlockedByModalPanel()) {
6097 // send QEvent::WindowBlocked to newly blocked panels
6098 sendEvent(item, &windowBlockedEvent);
6099 } else if (blockedPanels.contains(item) && !item->isBlockedByModalPanel()) {
6100 // send QEvent::WindowUnblocked to unblocked panels when downgrading
6101 // a panel from SceneModal to PanelModal
6102 sendEvent(item, &windowUnblockedEvent);
6103 }
6104 }
6105 }
6106}
6107
6108void QGraphicsScenePrivate::leaveModal(QGraphicsItem *panel)
6109{
6110 Q_Q(QGraphicsScene);
6111 Q_ASSERT(panel && panel->isPanel());
6112
6113 QSet<QGraphicsItem *> blockedPanels;
6114 {
6115 const auto items_ = q->items();
6116 for (const auto &item : items_) {
6117 if (item->isPanel() && item->isBlockedByModalPanel())
6118 blockedPanels.insert(item);
6119 }
6120 }
6121
6122 modalPanels.removeAll(panel);
6123
6124 {
6125 QEvent e(QEvent::WindowUnblocked);
6126 const auto items_ = q->items();
6127 for (const auto &item : items_) {
6128 if (item->isPanel() && blockedPanels.contains(item) && !item->isBlockedByModalPanel())
6129 sendEvent(item, &e);
6130 }
6131 }
6132
6133 // send GraphicsSceneHoverEnter events to newly unblocked items
6134 QGraphicsSceneHoverEvent hoverEvent;
6135 hoverEvent.setScenePos(lastSceneMousePos);
6136 dispatchHoverEvent(&hoverEvent);
6137}
6138
6139#ifndef QT_NO_GESTURES
6140void QGraphicsScenePrivate::gestureTargetsAtHotSpots(const QSet<QGesture *> &gestures,
6141 Qt::GestureFlag flag,
6142 QHash<QGraphicsObject *, QSet<QGesture *> > *targets,
6143 QSet<QGraphicsObject *> *itemsSet,
6144 QSet<QGesture *> *normal,
6145 QSet<QGesture *> *conflicts)
6146{
6147 QSet<QGesture *> normalGestures; // that are not in conflicted state.
6148 for (QGesture *gesture : gestures) {
6149 if (!gesture->hasHotSpot())
6150 continue;
6151 const Qt::GestureType gestureType = gesture->gestureType();
6152 const QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), gesture->d_func()->sceneHotSpot, nullptr);
6153 for (int j = 0; j < items.size(); ++j) {
6154 QGraphicsItem *item = items.at(j);
6155
6156 // Check if the item is blocked by a modal panel and use it as
6157 // a target instead of this item.
6158 (void) item->isBlockedByModalPanel(&item);
6159
6160 if (QGraphicsObject *itemobj = item->toGraphicsObject()) {
6161 QGraphicsItemPrivate *d = item->QGraphicsItem::d_func();
6162 QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator it =
6163 d->gestureContext.constFind(gestureType);
6164 if (it != d->gestureContext.constEnd() && (!flag || (it.value() & flag))) {
6165 if (normalGestures.contains(gesture)) {
6166 normalGestures.remove(gesture);
6167 if (conflicts)
6168 conflicts->insert(gesture);
6169 } else {
6170 normalGestures.insert(gesture);
6171 }
6172 if (targets)
6173 (*targets)[itemobj].insert(gesture);
6174 if (itemsSet)
6175 (*itemsSet).insert(itemobj);
6176 }
6177 }
6178 // Don't propagate through panels.
6179 if (item->isPanel())
6180 break;
6181 }
6182 }
6183 if (normal)
6184 *normal = normalGestures;
6185}
6186
6187void QGraphicsScenePrivate::gestureEventHandler(QGestureEvent *event)
6188{
6189 QWidget *viewport = event->widget();
6190 if (!viewport)
6191 return;
6192 QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(viewport->parent());
6193 if (!graphicsView)
6194 return;
6195
6196 const QList<QGesture *> allGestures = event->gestures();
6197 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6198 << "Gestures:" << allGestures;
6199
6200 QSet<QGesture *> startedGestures;
6201 QPoint delta = viewport->mapFromGlobal(QPoint());
6202 QTransform toScene = QTransform::fromTranslate(delta.x(), delta.y())
6203 * graphicsView->viewportTransform().inverted();
6204 for (QGesture *gesture : allGestures) {
6205 // cache scene coordinates of the hot spot
6206 if (gesture->hasHotSpot()) {
6207 gesture->d_func()->sceneHotSpot = toScene.map(gesture->hotSpot());
6208 } else {
6209 gesture->d_func()->sceneHotSpot = QPointF();
6210 }
6211
6212 QGraphicsObject *target = gestureTargets.value(gesture, 0);
6213 if (!target) {
6214 // when we are not in started mode but don't have a target
6215 // then the only one interested in gesture is the view/scene
6216 if (gesture->state() == Qt::GestureStarted)
6217 startedGestures.insert(gesture);
6218 }
6219 }
6220
6221 if (!startedGestures.isEmpty()) {
6222 QSet<QGesture *> normalGestures; // that have just one target
6223 QSet<QGesture *> conflictedGestures; // that have multiple possible targets
6224 gestureTargetsAtHotSpots(startedGestures, Qt::GestureFlag(0), &cachedItemGestures, nullptr,
6225 &normalGestures, &conflictedGestures);
6226 cachedTargetItems = cachedItemGestures.keys();
6227 std::sort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
6228 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6229 << "Normal gestures:" << normalGestures
6230 << "Conflicting gestures:" << conflictedGestures;
6231
6232 // deliver conflicted gestures as override events AND remember
6233 // initial gesture targets
6234 if (!conflictedGestures.isEmpty()) {
6235 for (int i = 0; i < cachedTargetItems.size(); ++i) {
6236 QPointer<QGraphicsObject> item = cachedTargetItems.at(i);
6237
6238 // get gestures to deliver to the current item
6239 const QSet<QGesture *> gestures = conflictedGestures & cachedItemGestures.value(item.data());
6240 if (gestures.isEmpty())
6241 continue;
6242
6243 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6244 << "delivering override to"
6245 << item.data() << gestures;
6246 // send gesture override
6247 QGestureEvent ev(gestures.values());
6248 ev.t = QEvent::GestureOverride;
6249 ev.setWidget(event->widget());
6250 // mark event and individual gestures as ignored
6251 ev.ignore();
6252 for (QGesture *g : gestures)
6253 ev.setAccepted(g, false);
6254 sendEvent(item.data(), &ev);
6255 // mark all accepted gestures to deliver them as normal gesture events
6256 for (QGesture *g : gestures) {
6257 if (ev.isAccepted() || ev.isAccepted(g)) {
6258 conflictedGestures.remove(g);
6259 // mark the item as a gesture target
6260 if (item) {
6261 gestureTargets.insert(g, item.data());
6262 QHash<QGraphicsObject *, QSet<QGesture *> >::iterator it, e;
6263 it = cachedItemGestures.begin();
6264 e = cachedItemGestures.end();
6265 for(; it != e; ++it)
6266 it.value().remove(g);
6267 cachedItemGestures[item.data()].insert(g);
6268 }
6269 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6270 << "override was accepted:"
6271 << g << item.data();
6272 }
6273 // remember the first item that received the override event
6274 // as it most likely become a target if no one else accepts
6275 // the override event
6276 if (!gestureTargets.contains(g) && item)
6277 gestureTargets.insert(g, item.data());
6278
6279 }
6280 if (conflictedGestures.isEmpty())
6281 break;
6282 }
6283 }
6284 // remember the initial target item for each gesture that was not in
6285 // the conflicted state.
6286 if (!normalGestures.isEmpty()) {
6287 for (int i = 0; i < cachedTargetItems.size() && !normalGestures.isEmpty(); ++i) {
6288 QGraphicsObject *item = cachedTargetItems.at(i);
6289
6290 // get gestures to deliver to the current item
6291 const auto gestures = cachedItemGestures.value(item);
6292 for (QGesture *g : gestures) {
6293 if (!gestureTargets.contains(g)) {
6294 gestureTargets.insert(g, item);
6295 normalGestures.remove(g);
6296 }
6297 }
6298 }
6299 }
6300 }
6301
6302
6303 // deliver all gesture events
6304 QSet<QGesture *> undeliveredGestures;
6305 QSet<QGesture *> parentPropagatedGestures;
6306 for (QGesture *gesture : allGestures) {
6307 if (QGraphicsObject *target = gestureTargets.value(gesture, 0)) {
6308 cachedItemGestures[target].insert(gesture);
6309 cachedTargetItems.append(target);
6310 undeliveredGestures.insert(gesture);
6311 QGraphicsItemPrivate *d = target->QGraphicsItem::d_func();
6312 const Qt::GestureFlags flags = d->gestureContext.value(gesture->gestureType());
6313 if (flags & Qt::IgnoredGesturesPropagateToParent)
6314 parentPropagatedGestures.insert(gesture);
6315 } else {
6316 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6317 << "no target for" << gesture << "at"
6318 << gesture->hotSpot() << gesture->d_func()->sceneHotSpot;
6319 }
6320 }
6321 std::sort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
6322 for (int i = 0; i < cachedTargetItems.size(); ++i) {
6323 QPointer<QGraphicsObject> receiver = cachedTargetItems.at(i);
6324 const QSet<QGesture *> gestures = (undeliveredGestures
6325 & cachedItemGestures.value(receiver.data()))
6326 - cachedAlreadyDeliveredGestures.value(receiver.data());
6327
6328 if (gestures.isEmpty())
6329 continue;
6330
6331 cachedAlreadyDeliveredGestures[receiver.data()] += gestures;
6332 const bool isPanel = receiver.data()->isPanel();
6333
6334 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6335 << "delivering to"
6336 << receiver.data() << gestures;
6337 QGestureEvent ev(gestures.values());
6338 ev.setWidget(event->widget());
6339 sendEvent(receiver.data(), &ev);
6340 QSet<QGesture *> ignoredGestures;
6341 for (QGesture *g : gestures) {
6342 if (!ev.isAccepted() && !ev.isAccepted(g)) {
6343 // if the gesture was ignored by its target, we will update the
6344 // targetItems list with a possible target items (items that
6345 // want to receive partial gestures).
6346 // ### won't work if the target was destroyed in the event
6347 // we will just stop delivering it.
6348 if (receiver && receiver.data() == gestureTargets.value(g, 0))
6349 ignoredGestures.insert(g);
6350 } else {
6351 if (receiver && g->state() == Qt::GestureStarted) {
6352 // someone accepted the propagated initial GestureStarted
6353 // event, let it be the new target for all following events.
6354 gestureTargets[g] = receiver.data();
6355 }
6356 undeliveredGestures.remove(g);
6357 }
6358 }
6359 if (undeliveredGestures.isEmpty())
6360 break;
6361
6362 // ignoredGestures list is only filled when delivering to the gesture
6363 // target item, so it is safe to assume item == target.
6364 if (!ignoredGestures.isEmpty() && !isPanel) {
6365 // look for new potential targets for gestures that were ignored
6366 // and should be propagated.
6367
6368 QSet<QGraphicsObject *> targetsSet(cachedTargetItems.constBegin(), cachedTargetItems.constEnd());
6369
6370 if (receiver) {
6371 // first if the gesture should be propagated to parents only
6372 for (QSet<QGesture *>::iterator it = ignoredGestures.begin();
6373 it != ignoredGestures.end();) {
6374 if (parentPropagatedGestures.contains(*it)) {
6375 QGesture *gesture = *it;
6376 const Qt::GestureType gestureType = gesture->gestureType();
6377 QGraphicsItem *item = receiver.data();
6378 while (item) {
6379 if (QGraphicsObject *obj = item->toGraphicsObject()) {
6380 if (item->d_func()->gestureContext.contains(gestureType)) {
6381 targetsSet.insert(obj);
6382 cachedItemGestures[obj].insert(gesture);
6383 }
6384 }
6385 if (item->isPanel())
6386 break;
6387 item = item->parentItem();
6388 }
6389
6390 it = ignoredGestures.erase(it);
6391 continue;
6392 }
6393 ++it;
6394 }
6395 }
6396
6397 gestureTargetsAtHotSpots(ignoredGestures, Qt::ReceivePartialGestures,
6398 &cachedItemGestures, &targetsSet, nullptr, nullptr);
6399
6400 cachedTargetItems = targetsSet.values();
6401 std::sort(cachedTargetItems.begin(), cachedTargetItems.end(), qt_closestItemFirst);
6402 DEBUG() << "QGraphicsScenePrivate::gestureEventHandler:"
6403 << "new targets:" << cachedTargetItems;
6404 i = -1; // start delivery again
6405 continue;
6406 }
6407 }
6408
6409 for (QGesture *g : std::as_const(startedGestures)) {
6410 if (g->gestureCancelPolicy() == QGesture::CancelAllInContext) {
6411 DEBUG() << "lets try to cancel some";
6412 // find gestures in context in Qt::GestureStarted or Qt::GestureUpdated state and cancel them
6413 cancelGesturesForChildren(g);
6414 }
6415 }
6416
6417 // forget about targets for gestures that have ended
6418 for (QGesture *g : allGestures) {
6419 switch (g->state()) {
6420 case Qt::GestureFinished:
6421 case Qt::GestureCanceled:
6422 gestureTargets.remove(g);
6423 break;
6424 default:
6425 break;
6426 }
6427 }
6428
6429 cachedTargetItems.clear();
6430 cachedItemGestures.clear();
6431 cachedAlreadyDeliveredGestures.clear();
6432}
6433
6434void QGraphicsScenePrivate::cancelGesturesForChildren(QGesture *original)
6435{
6436 Q_ASSERT(original);
6437 QGraphicsItem *originalItem = gestureTargets.value(original);
6438 if (originalItem == nullptr) // we only act on accepted gestures, which implies it has a target.
6439 return;
6440
6441 // iterate over all active gestures and for each find the owner
6442 // if the owner is part of our sub-hierarchy, cancel it.
6443
6444 QSet<QGesture *> canceledGestures;
6445 QHash<QGesture *, QGraphicsObject *>::Iterator iter = gestureTargets.begin();
6446 while (iter != gestureTargets.end()) {
6447 QGraphicsObject *item = iter.value();
6448 // note that we don't touch the gestures for our originalItem
6449 if (item != originalItem && originalItem->isAncestorOf(item)) {
6450 DEBUG() << " found a gesture to cancel" << iter.key();
6451 iter.key()->d_func()->state = Qt::GestureCanceled;
6452 canceledGestures << iter.key();
6453 }
6454 ++iter;
6455 }
6456
6457 // sort them per target item by cherry picking from almostCanceledGestures and delivering
6458 QSet<QGesture *> almostCanceledGestures = canceledGestures;
6459 QSet<QGesture *>::Iterator setIter;
6460 while (!almostCanceledGestures.isEmpty()) {
6461 QGraphicsObject *target = nullptr;
6462 QSet<QGesture*> gestures;
6463 setIter = almostCanceledGestures.begin();
6464 // sort per target item
6465 while (setIter != almostCanceledGestures.end()) {
6466 QGraphicsObject *item = gestureTargets.value(*setIter);
6467 if (target == nullptr)
6468 target = item;
6469 if (target == item) {
6470 gestures << *setIter;
6471 setIter = almostCanceledGestures.erase(setIter);
6472 } else {
6473 ++setIter;
6474 }
6475 }
6476 Q_ASSERT(target);
6477
6478 const QList<QGesture *> list = gestures.values();
6479 QGestureEvent ev(list);
6480 sendEvent(target, &ev);
6481
6482 if (!ev.isAccepted()) {
6483 for (QGesture *g : list) {
6484
6485 if (ev.isAccepted(g))
6486 continue;
6487
6488 if (!g->hasHotSpot())
6489 continue;
6490
6491 const QList<QGraphicsItem *> items = itemsAtPosition(QPoint(), g->d_func()->sceneHotSpot, nullptr);
6492 for (const auto &item : items) {
6493 QGraphicsObject *object = item->toGraphicsObject();
6494 if (!object)
6495 continue;
6496 QGraphicsItemPrivate *d = object->QGraphicsItem::d_func();
6497 if (d->gestureContext.contains(g->gestureType())) {
6498 QList<QGesture *> list;
6499 list << g;
6500 QGestureEvent ev(list);
6501 sendEvent(object, &ev);
6502 if (ev.isAccepted() || ev.isAccepted(g))
6503 break; // successfully delivered
6504 }
6505 }
6506 }
6507 }
6508 }
6509
6510 QGestureManager *gestureManager = QApplicationPrivate::instance()->gestureManager;
6511 Q_ASSERT(gestureManager); // it would be very odd if we got called without a manager.
6512 for (setIter = canceledGestures.begin(); setIter != canceledGestures.end(); ++setIter) {
6513 gestureManager->recycle(*setIter);
6514 gestureTargets.remove(*setIter);
6515 }
6516}
6517
6518void QGraphicsScenePrivate::grabGesture(QGraphicsItem *, Qt::GestureType gesture)
6519{
6520 (void)QGestureManager::instance(); // create a gesture manager
6521 if (!grabbedGestures[gesture]++) {
6522 for (QGraphicsView *view : std::as_const(views))
6523 view->viewport()->grabGesture(gesture);
6524 }
6525}
6526
6527void QGraphicsScenePrivate::ungrabGesture(QGraphicsItem *item, Qt::GestureType gesture)
6528{
6529 // we know this can only be an object
6530 Q_ASSERT(item->d_ptr->isObject);
6531 QGraphicsObject *obj = static_cast<QGraphicsObject *>(item);
6532 QGestureManager::instance()->cleanupCachedGestures(obj, gesture);
6533 if (!--grabbedGestures[gesture]) {
6534 for (QGraphicsView *view : std::as_const(views))
6535 view->viewport()->ungrabGesture(gesture);
6536 }
6537}
6538#endif // QT_NO_GESTURES
6539
6540QT_END_NAMESPACE
6541
6542#include "moc_qgraphicsscene.cpp"
friend class QPainter
friend class QWidget
Definition qpainter.h:432
Combined button and popup list for selecting options.
bool qt_sendSpontaneousEvent(QObject *, QEvent *)
static void setClip(QPainter *painter, QGraphicsItem *item)
static void _q_hoverFromMouseEvent(QGraphicsSceneHoverEvent *hover, const QGraphicsSceneMouseEvent *mouseEvent)
static void setWorldTransform(QPainter *painter, const QTransform *const transformPtr, const QTransform *effectTransform)
static bool transformIsSimple(const QTransform &transform)
#define ENSURE_TRANSFORM_PTR
static void _q_paintItem(QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget, bool useWindowOpacity, bool painterStateProtection)
static bool updateHelper(QGraphicsViewPrivate *view, QGraphicsItemPrivate *item, const QRectF &rect, bool itemIsUntransformable)
static void _q_paintIntoCache(QPixmap *pix, QGraphicsItem *item, const QRegion &pixmapExposed, const QTransform &itemToPixmap, QPainter::RenderHints renderHints, const QStyleOptionGraphicsItem *option, bool painterStateProtection)