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
qgraphicsview.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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
6
7static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < 2^9
8
9/*!
10 \class QGraphicsView
11 \brief The QGraphicsView class provides a widget for displaying the
12 contents of a QGraphicsScene.
13 \since 4.2
14 \ingroup graphicsview-api
15 \inmodule QtWidgets
16
17 QGraphicsView visualizes the contents of a QGraphicsScene in a scrollable
18 viewport. To create a scene with geometrical items, see QGraphicsScene's
19 documentation. QGraphicsView is part of the \l{Graphics View Framework}.
20
21 To visualize a scene, you start by constructing a QGraphicsView object,
22 passing the address of the scene you want to visualize to QGraphicsView's
23 constructor. Alternatively, you can call setScene() to set the scene at a
24 later point. After you call show(), the view will by default scroll to the
25 center of the scene and display any items that are visible at this
26 point. For example:
27
28 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 0
29
30 You can explicitly scroll to any position on the scene by using the
31 scroll bars, or by calling centerOn(). By passing a point to centerOn(),
32 QGraphicsView will scroll its viewport to ensure that the point is
33 centered in the view. An overload is provided for scrolling to a
34 QGraphicsItem, in which case QGraphicsView will see to that the center of
35 the item is centered in the view. If all you want is to ensure that a
36 certain area is visible, (but not necessarily centered,) you can call
37 ensureVisible() instead.
38
39 QGraphicsView can be used to visualize a whole scene, or only parts of it.
40 The visualized area is by default detected automatically when the view is
41 displayed for the first time (by calling
42 QGraphicsScene::itemsBoundingRect()). To set the visualized area rectangle
43 yourself, you can call setSceneRect(). This will adjust the scroll bars'
44 ranges appropriately. Note that although the scene supports a virtually
45 unlimited size, the range of the scroll bars will never exceed the range of
46 an integer (INT_MIN, INT_MAX).
47
48 QGraphicsView visualizes the scene by calling render(). By default, the
49 items are drawn onto the viewport by using a regular QPainter, and using
50 default render hints. To change the default render hints that
51 QGraphicsView passes to QPainter when painting items, you can call
52 setRenderHints().
53
54 By default, QGraphicsView provides a regular QWidget for the viewport
55 widget. You can access this widget by calling viewport(), or you can
56 replace it by calling setViewport(). To render using OpenGL, simply call
57 setViewport(new QOpenGLWidget). QGraphicsView takes ownership of the
58 viewport widget.
59
60 QGraphicsView supports affine transformations, using QTransform. You can
61 either pass a matrix to setTransform(), or you can call one of the
62 convenience functions rotate(), scale(), translate() or shear(). The most
63 two common transformations are scaling, which is used to implement
64 zooming, and rotation. QGraphicsView keeps the center of the view fixed
65 during a transformation. Because of the scene alignment (setAlignment()),
66 translating the view will have no visual impact.
67
68 You can interact with the items on the scene by using the mouse and
69 keyboard. QGraphicsView translates the mouse and key events into \e scene
70 events, (events that inherit QGraphicsSceneEvent,), and forward them to
71 the visualized scene. In the end, it's the individual item that handles
72 the events and reacts to them. For example, if you click on a selectable
73 item, the item will typically let the scene know that it has been
74 selected, and it will also redraw itself to display a selection
75 rectangle. Similarly, if you click and drag the mouse to move a movable
76 item, it's the item that handles the mouse moves and moves itself. Item
77 interaction is enabled by default, and you can toggle it by calling
78 setInteractive().
79
80 You can also provide your own custom scene interaction, by creating a
81 subclass of QGraphicsView, and reimplementing the mouse and key event
82 handlers. To simplify how you programmatically interact with items in the
83 view, QGraphicsView provides the mapping functions mapToScene() and
84 mapFromScene(), and the item accessors items() and itemAt(). These
85 functions allow you to map points, rectangles, polygons and paths between
86 view coordinates and scene coordinates, and to find items on the scene
87 using view coordinates.
88
89 When using a QOpenGLWidget as a viewport, stereoscopic rendering is
90 supported. This is done using the same pattern as QOpenGLWidget::paintGL.
91 To enable it, enable the QSurfaceFormat::StereoBuffers flag. Because of
92 how the flag is handled internally, set QSurfaceFormat::StereoBuffers flag
93 globally before the window is created using QSurfaceFormat::setDefaultFormat().
94 If the flag is enabled and there is hardware support for stereoscopic
95 rendering, then drawBackground() and drawForeground() will be triggered twice
96 each frame. Call QOpenGLWidget::currentTargetBuffer() to query which buffer
97 is currently being drawn to.
98
99 \image graphicsview-view.png {Grid of computer chips}
100
101 \note Using an OpenGL viewport limits the ability to use QGraphicsProxyWidget.
102 Not all combinations of widgets and styles can be supported with such a setup.
103 You should carefully test your UI and make the necessary adjustments.
104
105 \sa QGraphicsScene, QGraphicsItem, QGraphicsSceneEvent
106*/
107
108/*!
109 \enum QGraphicsView::ViewportAnchor
110
111 This enums describe the possible anchors that QGraphicsView can
112 use when the user resizes the view or when the view is
113 transformed.
114
115 \value NoAnchor No anchor, i.e. the view leaves the scene's
116 position unchanged.
117 \value AnchorViewCenter The scene point at the center of the view
118 is used as the anchor.
119 \value AnchorUnderMouse The point under the mouse is used as the anchor.
120
121 \sa resizeAnchor, transformationAnchor
122*/
123
124/*!
125 \enum QGraphicsView::ViewportUpdateMode
126
127 \since 4.3
128
129 This enum describes how QGraphicsView updates its viewport when the scene
130 contents change or are exposed.
131
132 \value FullViewportUpdate When any visible part of the scene changes or is
133 reexposed, QGraphicsView will update the entire viewport. This approach is
134 fastest when QGraphicsView spends more time figuring out what to draw than
135 it would spend drawing (e.g., when very many small items are repeatedly
136 updated). This is the preferred update mode for viewports that do not
137 support partial updates, such as QOpenGLWidget, and for viewports that
138 need to disable scroll optimization.
139
140 \value MinimalViewportUpdate QGraphicsView will determine the minimal
141 viewport region that requires a redraw, minimizing the time spent drawing
142 by avoiding a redraw of areas that have not changed. This is
143 QGraphicsView's default mode. Although this approach provides the best
144 performance in general, if there are many small visible changes on the
145 scene, QGraphicsView might end up spending more time finding the minimal
146 approach than it will spend drawing.
147
148 \value SmartViewportUpdate QGraphicsView will attempt to find an optimal
149 update mode by analyzing the areas that require a redraw.
150
151 \value BoundingRectViewportUpdate The bounding rectangle of all changes in
152 the viewport will be redrawn. This mode has the advantage that
153 QGraphicsView searches only one region for changes, minimizing time spent
154 determining what needs redrawing. The disadvantage is that areas that have
155 not changed also need to be redrawn.
156
157 \value NoViewportUpdate QGraphicsView will never update its viewport when
158 the scene changes; the user is expected to control all updates. This mode
159 disables all (potentially slow) item visibility testing in QGraphicsView,
160 and is suitable for scenes that either require a fixed frame rate, or where
161 the viewport is otherwise updated externally.
162
163 \sa viewportUpdateMode
164*/
165
166/*!
167 \enum QGraphicsView::OptimizationFlag
168
169 \since 4.3
170
171 This enum describes flags that you can enable to improve rendering
172 performance in QGraphicsView. By default, none of these flags are set.
173 Note that setting a flag usually imposes a side effect, and this effect
174 can vary between paint devices and platforms.
175
176 \value DontSavePainterState When rendering, QGraphicsView protects the
177 painter state (see QPainter::save()) when rendering the background or
178 foreground, and when rendering each item. This allows you to leave the
179 painter in an altered state (i.e., you can call QPainter::setPen() or
180 QPainter::setBrush() without restoring the state after painting). However,
181 if the items consistently do restore the state, you should enable this
182 flag to prevent QGraphicsView from doing the same.
183
184 \value DontAdjustForAntialiasing Disables QGraphicsView's antialiasing
185 auto-adjustment of exposed areas. Items that render antialiased lines on
186 the boundaries of their QGraphicsItem::boundingRect() can end up rendering
187 parts of the line outside. To prevent rendering artifacts, QGraphicsView
188 expands all exposed regions by 2 pixels in all directions. If you enable
189 this flag, QGraphicsView will no longer perform these adjustments,
190 minimizing the areas that require redrawing, which improves performance. A
191 common side effect is that items that do draw with antialiasing can leave
192 painting traces behind on the scene as they are moved.
193
194 \value IndirectPainting Since Qt 4.6, restore the old painting algorithm
195 that calls QGraphicsView::drawItems() and QGraphicsScene::drawItems().
196 To be used only for compatibility with old code.
197*/
198
199/*!
200 \enum QGraphicsView::CacheModeFlag
201
202 This enum describes the flags that you can set for a QGraphicsView's cache
203 mode.
204
205 \value CacheNone All painting is done directly onto the viewport.
206
207 \value CacheBackground The background is cached. This affects both custom
208 backgrounds, and backgrounds based on the backgroundBrush property. When
209 this flag is enabled, QGraphicsView will allocate one pixmap with the full
210 size of the viewport.
211
212 \sa cacheMode
213*/
214
215/*!
216 \enum QGraphicsView::DragMode
217
218 This enum describes the default action for the view when pressing and
219 dragging the mouse over the viewport.
220
221 \value NoDrag Nothing happens; the mouse event is ignored.
222
223 \value ScrollHandDrag The cursor changes into a pointing hand, and
224 dragging the mouse around will scroll the scrolbars. This mode works both
225 in \l{QGraphicsView::interactive}{interactive} and non-interactive mode.
226
227 \value RubberBandDrag A rubber band will appear. Dragging the mouse will
228 set the rubber band geometry, and all items covered by the rubber band are
229 selected. This mode is disabled for non-interactive views.
230
231 \sa dragMode, QGraphicsScene::setSelectionArea()
232*/
233
234/*!
235 \since 5.1
236
237 \fn void QGraphicsView::rubberBandChanged(QRect rubberBandRect, QPointF fromScenePoint, QPointF toScenePoint)
238
239 This signal is emitted when the rubber band rect is changed. The viewport Rect is specified by \a rubberBandRect.
240 The drag start position and drag end position are provided in scene points with \a fromScenePoint and \a toScenePoint.
241
242 When rubberband selection ends this signal will be emitted with null vales.
243
244 \sa rubberBandRect()
245*/
246
247
248#include "qgraphicsview.h"
249#include "qgraphicsview_p.h"
250
251#include "qgraphicsitem.h"
252#include "qgraphicsitem_p.h"
253#include "qgraphicsscene.h"
256#include "qgraphicswidget.h"
257
258#include <QtCore/qdatetime.h>
259#include <QtCore/qdebug.h>
260#include <QtCore/qmath.h>
261#include <QtCore/qscopedvaluerollback.h>
262#include <QtWidgets/qapplication.h>
263#include <QtWidgets/qgesture.h>
264#include <QtGui/qevent.h>
265#include <QtWidgets/qlayout.h>
266#include <QtGui/qtransform.h>
267#include <QtGui/qpainter.h>
268#include <QtGui/qpainterpath.h>
269#include <QtWidgets/qscrollbar.h>
270#include <QtWidgets/qstyleoption.h>
271
272#include <private/qevent_p.h>
273#include <QtGui/private/qeventpoint_p.h>
274
276
277bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
278
279inline int q_round_bound(qreal d) //### (int)(qreal) INT_MAX != INT_MAX for single precision
280{
281 if (d <= (qreal) INT_MIN)
282 return INT_MIN;
283 else if (d >= (qreal) INT_MAX)
284 return INT_MAX;
285 return d >= 0.0 ? int(d + 0.5) : int(d - int(d-1) + 0.5) + int(d-1);
286}
287
288void QGraphicsViewPrivate::translateTouchEvent(QGraphicsViewPrivate *d, QTouchEvent *touchEvent)
289{
290 for (int i = 0; i < touchEvent->pointCount(); ++i) {
291 auto &pt = touchEvent->point(i);
292 // the scene will set the item local pos, startPos, lastPos, and rect before delivering to
293 // an item, but for now those functions are returning the view's local coordinates
294 QMutableEventPoint::setScenePosition(pt, d->mapToScene(pt.position()));
295 // screenPos, startScreenPos, and lastScreenPos are already set
296 }
297}
298
299/*!
300 \internal
301*/
302QGraphicsViewPrivate::QGraphicsViewPrivate()
303 : renderHints(QPainter::TextAntialiasing),
304 dragMode(QGraphicsView::NoDrag),
305 sceneInteractionAllowed(true), hasSceneRect(false),
306 connectedToScene(false),
307 useLastMouseEvent(false),
308 identityMatrix(true),
309 dirtyScroll(true),
310 accelerateScrolling(true),
311 keepLastCenterPoint(true),
312 transforming(false),
313 handScrolling(false),
314 mustAllocateStyleOptions(false),
315 mustResizeBackgroundPixmap(true),
316 fullUpdatePending(true),
317 hasUpdateClip(false),
318 mousePressButton(Qt::NoButton),
319 leftIndent(0), topIndent(0),
320 alignment(Qt::AlignCenter),
321 transformationAnchor(QGraphicsView::AnchorViewCenter), resizeAnchor(QGraphicsView::NoAnchor),
322 viewportUpdateMode(QGraphicsView::MinimalViewportUpdate),
323 scene(nullptr),
324#if QT_CONFIG(rubberband)
325 rubberBanding(false),
326 rubberBandSelectionMode(Qt::IntersectsItemShape),
327 rubberBandSelectionOperation(Qt::ReplaceSelection),
328#endif
329 handScrollMotions(0),
330#ifndef QT_NO_CURSOR
331 hasStoredOriginalCursor(false),
332#endif
333 lastDragDropEvent(nullptr),
334 updateSceneSlotReimplementedChecked(false)
335{
336 styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS);
337}
338
339QGraphicsViewPrivate::~QGraphicsViewPrivate()
340{
341}
342
343/*!
344 \internal
345*/
346void QGraphicsViewPrivate::recalculateContentSize()
347{
348 Q_Q(QGraphicsView);
349
350 const QSize maxSize = q->maximumViewportSize();
351 int width = maxSize.width();
352 int height = maxSize.height();
353 const QRectF viewRect = matrix.mapRect(q->sceneRect());
354
355 bool frameOnlyAround = (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, nullptr, q));
356 if (frameOnlyAround) {
357 if (hbarpolicy == Qt::ScrollBarAlwaysOn)
358 height -= frameWidth * 2;
359 if (vbarpolicy == Qt::ScrollBarAlwaysOn)
360 width -= frameWidth * 2;
361 }
362
363 // Adjust the maximum width and height of the viewport based on the width
364 // of visible scroll bars.
365 const int scrollBarExtent = q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, nullptr, q)
366 + (frameOnlyAround ? frameWidth * 2 : 0);
367
368 // We do not need to subtract the width scrollbars whose policy is
369 // Qt::ScrollBarAlwaysOn, this was already done by maximumViewportSize().
370 bool useHorizontalScrollBar = (viewRect.width() > width) && hbarpolicy == Qt::ScrollBarAsNeeded;
371 bool useVerticalScrollBar = (viewRect.height() > height) && vbarpolicy == Qt::ScrollBarAsNeeded;
372 if (useHorizontalScrollBar && vbarpolicy == Qt::ScrollBarAsNeeded) {
373 if (viewRect.height() > height - scrollBarExtent)
374 useVerticalScrollBar = true;
375 }
376 if (useVerticalScrollBar && hbarpolicy == Qt::ScrollBarAsNeeded) {
377 if (viewRect.width() > width - scrollBarExtent)
378 useHorizontalScrollBar = true;
379 }
380 if (useHorizontalScrollBar)
381 height -= scrollBarExtent;
382 if (useVerticalScrollBar)
383 width -= scrollBarExtent;
384
385 // Setting the ranges of these scroll bars can/will cause the values to
386 // change, and scrollContentsBy() will be called correspondingly. This
387 // will reset the last center point.
388 const QPointF savedLastCenterPoint = lastCenterPoint;
389
390 // Remember the former indent settings
391 const qreal oldLeftIndent = leftIndent;
392 const qreal oldTopIndent = topIndent;
393
394 const auto singleStep = defaultSingleStep();
395
396 // If the whole scene fits horizontally, we center the scene horizontally,
397 // and ignore the horizontal scroll bars.
398 const int left = q_round_bound(viewRect.left());
399 const int right = q_round_bound(viewRect.right() - width);
400 if (left >= right) {
401 switch (alignment & Qt::AlignHorizontal_Mask) {
402 case Qt::AlignLeft:
403 leftIndent = -viewRect.left();
404 break;
405 case Qt::AlignRight:
406 leftIndent = maxSize.width() - viewRect.width() - viewRect.left() - 1;
407 break;
408 case Qt::AlignHCenter:
409 default:
410 leftIndent = maxSize.width() / 2 - (viewRect.left() + viewRect.right()) / 2;
411 break;
412 }
413
414 hbar->setRange(0, 0);
415 } else {
416 leftIndent = 0;
417
418 hbar->setRange(left, right);
419 hbar->setPageStep(width);
420 hbar->setSingleStep(width / singleStep);
421
422 if (oldLeftIndent != 0)
423 hbar->setValue(-oldLeftIndent);
424 }
425
426 // If the whole scene fits vertically, we center the scene vertically, and
427 // ignore the vertical scroll bars.
428 const int top = q_round_bound(viewRect.top());
429 const int bottom = q_round_bound(viewRect.bottom() - height);
430 if (top >= bottom) {
431 switch (alignment & Qt::AlignVertical_Mask) {
432 case Qt::AlignTop:
433 topIndent = -viewRect.top();
434 break;
435 case Qt::AlignBottom:
436 topIndent = maxSize.height() - viewRect.height() - viewRect.top() - 1;
437 break;
438 case Qt::AlignVCenter:
439 default:
440 topIndent = maxSize.height() / 2 - (viewRect.top() + viewRect.bottom()) / 2;
441 break;
442 }
443
444 vbar->setRange(0, 0);
445 } else {
446 topIndent = 0;
447
448 vbar->setRange(top, bottom);
449 vbar->setPageStep(height);
450 vbar->setSingleStep(height / singleStep);
451
452 if (oldTopIndent != 0)
453 vbar->setValue(-oldTopIndent);
454 }
455
456 // Restorethe center point from before the ranges changed.
457 lastCenterPoint = savedLastCenterPoint;
458
459 // Issue a full update if the indents change.
460 // ### If the transform is still the same, we can get away with just a
461 // scroll instead.
462 if (oldLeftIndent != leftIndent || oldTopIndent != topIndent) {
463 dirtyScroll = true;
464 updateAll();
465 } else if (q->isRightToLeft() && !leftIndent) {
466 // In reverse mode, the horizontal scroll always changes after the content
467 // size has changed, as the scroll is calculated by summing the min and
468 // max values of the range and subtracting the current value. In normal
469 // mode the scroll remains unchanged unless the indent has changed.
470 dirtyScroll = true;
471 }
472
473 if (cacheMode & QGraphicsView::CacheBackground) {
474 // Invalidate the background pixmap
475 mustResizeBackgroundPixmap = true;
476 }
477}
478
479/*!
480 \internal
481*/
482void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor)
483{
484 Q_Q(QGraphicsView);
485 switch (anchor) {
486 case QGraphicsView::AnchorUnderMouse: {
487 if (q->underMouse()) {
488 // Last scene pos: lastMouseMoveScenePoint
489 // Current mouse pos:
490 QPointF transformationDiff = mapToScene(viewport->rect().toRectF().center())
491 - mapToScene(viewport->mapFromGlobal(QCursor::pos().toPointF()));
492 q->centerOn(lastMouseMoveScenePoint + transformationDiff);
493 } else {
494 q->centerOn(lastCenterPoint);
495 }
496 break;
497 }
498 case QGraphicsView::AnchorViewCenter:
499 q->centerOn(lastCenterPoint);
500 break;
501 case QGraphicsView::NoAnchor:
502 break;
503 }
504}
505
506/*!
507 \internal
508*/
509void QGraphicsViewPrivate::updateLastCenterPoint()
510{
511 lastCenterPoint = mapToScene(viewport->rect().toRectF().center());
512}
513
514/*!
515 \internal
516
517 Returns the horizontal scroll value (the X value of the left edge of the
518 viewport).
519*/
520qint64 QGraphicsViewPrivate::horizontalScroll() const
521{
522 if (dirtyScroll)
523 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
524 return scrollX;
525}
526
527/*!
528 \internal
529
530 Returns the vertical scroll value (the X value of the top edge of the
531 viewport).
532*/
533qint64 QGraphicsViewPrivate::verticalScroll() const
534{
535 if (dirtyScroll)
536 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
537 return scrollY;
538}
539
540/*!
541 \internal
542
543 Maps the given rectangle to the scene using QTransform::mapRect()
544*/
545QRectF QGraphicsViewPrivate::mapRectToScene(const QRect &rect) const
546{
547 if (dirtyScroll)
548 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
549 QRectF scrolled = QRectF(rect.translated(scrollX, scrollY));
550 return identityMatrix ? scrolled : matrix.inverted().mapRect(scrolled);
551}
552
553
554/*!
555 \internal
556
557 Maps the given rectangle from the scene using QTransform::mapRect()
558*/
559QRectF QGraphicsViewPrivate::mapRectFromScene(const QRectF &rect) const
560{
561 if (dirtyScroll)
562 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
563 return (identityMatrix ? rect : matrix.mapRect(rect)).translated(-scrollX, -scrollY);
564}
565
566/*!
567 \internal
568*/
569void QGraphicsViewPrivate::updateScroll()
570{
571 Q_Q(QGraphicsView);
572 scrollX = qint64(-leftIndent);
573 if (q->isRightToLeft()) {
574 if (!leftIndent) {
575 scrollX += hbar->minimum();
576 scrollX += hbar->maximum();
577 scrollX -= hbar->value();
578 }
579 } else {
580 scrollX += hbar->value();
581 }
582
583 scrollY = qint64(vbar->value() - topIndent);
584
585 dirtyScroll = false;
586}
587
588/*!
589 \internal
590
591 * don't start scrolling when a drag mode has been set
592 * don't start scrolling on a movable item
593*/
594bool QGraphicsViewPrivate::canStartScrollingAt(const QPoint &startPos) const
595{
596 Q_Q(const QGraphicsView);
597 if (q->dragMode() != QGraphicsView::NoDrag)
598 return false;
599
600 const QGraphicsItem *childItem = q->itemAt(startPos);
601
602 if (!startPos.isNull() && childItem && (childItem->flags() & QGraphicsItem::ItemIsMovable))
603 return false;
604
605 return QAbstractScrollAreaPrivate::canStartScrollingAt(startPos);
606}
607
608/*!
609 \internal
610*/
611void QGraphicsViewPrivate::replayLastMouseEvent()
612{
613 if (!useLastMouseEvent || !scene)
614 return;
615 mouseMoveEventHandler(&*lastMouseEvent);
616}
617
618/*!
619 \internal
620*/
621void QGraphicsViewPrivate::storeMouseEvent(QMouseEvent *event)
622{
623 useLastMouseEvent = true;
624 // *event may alias *lastMouseEvent
625 lastMouseEvent.storeUnlessAlias(*event);
626}
627
628void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event)
629{
630 Q_Q(QGraphicsView);
631
632#if QT_CONFIG(rubberband)
633 updateRubberBand(event);
634#endif
635
636 storeMouseEvent(event);
637 lastMouseEvent->setAccepted(false);
638
639 if (!sceneInteractionAllowed)
640 return;
641 if (handScrolling)
642 return;
643 if (!scene)
644 return;
645
646 QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);
647 mouseEvent.setWidget(viewport);
648 mouseEvent.setButtonDownScenePos(mousePressButton, mousePressScenePoint);
649 mouseEvent.setButtonDownScreenPos(mousePressButton, mousePressScreenPoint);
650 mouseEvent.setScenePos(q->mapToScene(event->position().toPoint()));
651 mouseEvent.setScreenPos(event->globalPosition().toPoint());
652 mouseEvent.setLastScenePos(lastMouseMoveScenePoint);
653 mouseEvent.setLastScreenPos(lastMouseMoveScreenPoint);
654 mouseEvent.setButtons(event->buttons());
655 mouseEvent.setButton(event->button());
656 mouseEvent.setModifiers(event->modifiers());
657 mouseEvent.setSource(event->source());
658 mouseEvent.setFlags(event->flags());
659 mouseEvent.setTimestamp(event->timestamp());
660 lastMouseMoveScenePoint = mouseEvent.scenePos();
661 lastMouseMoveScreenPoint = mouseEvent.screenPos();
662 mouseEvent.setAccepted(false);
663 if (event->spontaneous())
664 qt_sendSpontaneousEvent(scene, &mouseEvent);
665 else
666 QCoreApplication::sendEvent(scene, &mouseEvent);
667
668 // Remember whether the last event was accepted or not.
669 lastMouseEvent->setAccepted(mouseEvent.isAccepted());
670
671 if (mouseEvent.isAccepted() && mouseEvent.buttons() != 0) {
672 // The event was delivered to a mouse grabber; the press is likely to
673 // have set a cursor, and we must not change it.
674 return;
675 }
676
677#ifndef QT_NO_CURSOR
678 // If all the items ignore hover events, we don't look-up any items
679 // in QGraphicsScenePrivate::dispatchHoverEvent, hence the
680 // cachedItemsUnderMouse list will be empty. We therefore do the look-up
681 // for cursor items here if not all items use the default cursor.
682 if (scene->d_func()->allItemsIgnoreHoverEvents && !scene->d_func()->allItemsUseDefaultCursor
683 && scene->d_func()->cachedItemsUnderMouse.isEmpty()) {
684 scene->d_func()->cachedItemsUnderMouse = scene->d_func()->itemsAtPosition(mouseEvent.screenPos(),
685 mouseEvent.scenePos(),
686 mouseEvent.widget());
687 }
688 // Find the topmost item under the mouse with a cursor.
689 for (QGraphicsItem *item : std::as_const(scene->d_func()->cachedItemsUnderMouse)) {
690 if (item->isEnabled() && item->hasCursor()) {
691 _q_setViewportCursor(item->cursor());
692 return;
693 }
694 }
695
696 // No items with cursors found; revert to the view cursor.
697 if (hasStoredOriginalCursor) {
698 // Restore the original viewport cursor.
699 hasStoredOriginalCursor = false;
700 viewport->setCursor(originalCursor);
701 }
702#endif
703}
704
705/*!
706 \internal
707*/
708#if QT_CONFIG(rubberband)
709QRegion QGraphicsViewPrivate::rubberBandRegion(const QWidget *widget, const QRect &rect) const
710{
711 QStyleHintReturnMask mask;
712 QStyleOptionRubberBand option;
713 option.initFrom(widget);
714 option.rect = rect;
715 option.opaque = false;
716 option.shape = QRubberBand::Rectangle;
717
718 QRegion tmp;
719 tmp += rect.adjusted(-1, -1, 1, 1);
720 if (widget->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, widget, &mask))
721 tmp &= mask.region;
722 return tmp;
723}
724
725void QGraphicsViewPrivate::updateRubberBand(const QMouseEvent *event)
726{
727 Q_Q(QGraphicsView);
728 if (dragMode != QGraphicsView::RubberBandDrag || !sceneInteractionAllowed || !rubberBanding)
729 return;
730 // Check for enough drag distance
731 if ((mousePressViewPoint - event->position().toPoint()).manhattanLength() < QApplication::startDragDistance())
732 return;
733
734 // Update old rubberband
735 if (viewportUpdateMode != QGraphicsView::NoViewportUpdate && !rubberBandRect.isEmpty()) {
736 if (viewportUpdateMode != QGraphicsView::FullViewportUpdate)
737 q->viewport()->update(rubberBandRegion(q->viewport(), rubberBandRect));
738 else
739 updateAll();
740 }
741
742 // Stop rubber banding if the user has let go of all buttons (even
743 // if we didn't get the release events).
744 if (!event->buttons()) {
745 rubberBanding = false;
746 rubberBandSelectionOperation = Qt::ReplaceSelection;
747 if (!rubberBandRect.isNull()) {
748 rubberBandRect = QRect();
749 emit q->rubberBandChanged(rubberBandRect, QPointF(), QPointF());
750 }
751 return;
752 }
753
754 QRect oldRubberband = rubberBandRect;
755
756 // Update rubberband position
757 const QPoint mp = q->mapFromScene(mousePressScenePoint);
758 const QPoint ep = event->position().toPoint();
759 rubberBandRect = QRect(qMin(mp.x(), ep.x()), qMin(mp.y(), ep.y()),
760 qAbs(mp.x() - ep.x()) + 1, qAbs(mp.y() - ep.y()) + 1);
761
762 if (rubberBandRect != oldRubberband || lastRubberbandScenePoint != lastMouseMoveScenePoint) {
763 lastRubberbandScenePoint = lastMouseMoveScenePoint;
764 oldRubberband = rubberBandRect;
765 emit q->rubberBandChanged(rubberBandRect, mousePressScenePoint, lastRubberbandScenePoint);
766 }
767
768 // Update new rubberband
769 if (viewportUpdateMode != QGraphicsView::NoViewportUpdate) {
770 if (viewportUpdateMode != QGraphicsView::FullViewportUpdate)
771 q->viewport()->update(rubberBandRegion(q->viewport(), rubberBandRect));
772 else
773 updateAll();
774 }
775 // Set the new selection area
776 QPainterPath selectionArea;
777 selectionArea.addPolygon(q->mapToScene(rubberBandRect));
778 selectionArea.closeSubpath();
779 if (scene)
780 scene->setSelectionArea(selectionArea, rubberBandSelectionOperation, rubberBandSelectionMode, q->viewportTransform());
781}
782
783void QGraphicsViewPrivate::clearRubberBand()
784{
785 Q_Q(QGraphicsView);
786 if (dragMode != QGraphicsView::RubberBandDrag || !sceneInteractionAllowed || !rubberBanding)
787 return;
788
789 if (viewportUpdateMode != QGraphicsView::NoViewportUpdate) {
790 if (viewportUpdateMode != QGraphicsView::FullViewportUpdate)
791 q->viewport()->update(rubberBandRegion(q->viewport(), rubberBandRect));
792 else
793 updateAll();
794 }
795
796 rubberBanding = false;
797 rubberBandSelectionOperation = Qt::ReplaceSelection;
798 if (!rubberBandRect.isNull()) {
799 rubberBandRect = QRect();
800 emit q->rubberBandChanged(rubberBandRect, QPointF(), QPointF());
801 }
802}
803#endif
804
805/*!
806 \internal
807*/
808#ifndef QT_NO_CURSOR
809void QGraphicsViewPrivate::_q_setViewportCursor(const QCursor &cursor)
810{
811 if (!hasStoredOriginalCursor) {
812 hasStoredOriginalCursor = true;
813 originalCursor = viewport->cursor();
814 }
815 viewport->setCursor(cursor);
816}
817#endif
818
819/*!
820 \internal
821*/
822#ifndef QT_NO_CURSOR
823void QGraphicsViewPrivate::_q_unsetViewportCursor()
824{
825 Q_Q(QGraphicsView);
826 const auto items = q->items(lastMouseEvent->position().toPoint());
827 for (QGraphicsItem *item : items) {
828 if (item->isEnabled() && item->hasCursor()) {
829 _q_setViewportCursor(item->cursor());
830 return;
831 }
832 }
833
834 // Restore the original viewport cursor.
835 if (hasStoredOriginalCursor) {
836 hasStoredOriginalCursor = false;
837 if (dragMode == QGraphicsView::ScrollHandDrag)
838 viewport->setCursor(Qt::OpenHandCursor);
839 else
840 viewport->setCursor(originalCursor);
841 }
842}
843#endif
844
845/*!
846 \internal
847*/
848void QGraphicsViewPrivate::storeDragDropEvent(const QGraphicsSceneDragDropEvent *event)
849{
850 delete lastDragDropEvent;
851 lastDragDropEvent = new QGraphicsSceneDragDropEvent(event->type());
852 lastDragDropEvent->setScenePos(event->scenePos());
853 lastDragDropEvent->setScreenPos(event->screenPos());
854 lastDragDropEvent->setButtons(event->buttons());
855 lastDragDropEvent->setModifiers(event->modifiers());
856 lastDragDropEvent->setPossibleActions(event->possibleActions());
857 lastDragDropEvent->setProposedAction(event->proposedAction());
858 lastDragDropEvent->setDropAction(event->dropAction());
859 lastDragDropEvent->setMimeData(event->mimeData());
860 lastDragDropEvent->setWidget(event->widget());
861 lastDragDropEvent->setSource(event->source());
862 lastDragDropEvent->setTimestamp(event->timestamp());
863}
864
865/*!
866 \internal
867*/
868void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEvent *dest,
869 QDropEvent *source)
870{
871#if QT_CONFIG(draganddrop)
872 Q_Q(QGraphicsView);
873 dest->setScenePos(q->mapToScene(source->position().toPoint()));
874 dest->setScreenPos(q->mapToGlobal(source->position()).toPoint());
875 dest->setButtons(source->buttons());
876 dest->setModifiers(source->modifiers());
877 dest->setPossibleActions(source->possibleActions());
878 dest->setProposedAction(source->proposedAction());
879 dest->setDropAction(source->dropAction());
880 dest->setMimeData(source->mimeData());
881 dest->setWidget(viewport);
882 dest->setSource(qobject_cast<QWidget *>(source->source()));
883#else
884 Q_UNUSED(dest);
885 Q_UNUSED(source);
886#endif
887}
888
889/*!
890 \internal
891*/
892QTransform QGraphicsViewPrivate::mapToViewTransform(const QGraphicsItem *item) const
893{
894 Q_Q(const QGraphicsView);
895 if (dirtyScroll)
896 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
897
898 if (item->d_ptr->itemIsUntransformable())
899 return item->deviceTransform(q->viewportTransform());
900
901 // Translate-only
902 // COMBINE
903 QPointF offset;
904 const QGraphicsItem *parentItem = item;
905 const QGraphicsItemPrivate *itemd;
906 do {
907 itemd = parentItem->d_ptr.data();
908 if (itemd->transformData)
909 break;
910 offset += itemd->pos;
911 } while ((parentItem = itemd->parent));
912
913 QTransform move = QTransform::fromTranslate(offset.x(), offset.y());
914 if (!parentItem) {
915 move.translate(-scrollX, -scrollY);
916 return identityMatrix ? move : matrix * move;
917 }
918 QTransform tr = parentItem->sceneTransform();
919 if (!identityMatrix)
920 tr *= matrix;
921 return move * tr * QTransform::fromTranslate(-scrollX, -scrollY);
922}
923
924QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRectF &rect) const
925{
926 return mapToViewTransform(item).mapRect(rect).toAlignedRect();
927}
928
929/*!
930 \internal
931*/
932QRegion QGraphicsViewPrivate::mapToViewRegion(const QGraphicsItem *item, const QRectF &rect) const
933{
934 Q_Q(const QGraphicsView);
935 if (dirtyScroll)
936 const_cast<QGraphicsViewPrivate *>(this)->updateScroll();
937
938 // Accurate bounding region
939 QTransform itv = item->deviceTransform(q->viewportTransform());
940 return item->boundingRegion(itv) & itv.mapRect(rect).toAlignedRect();
941}
942
943/*!
944 \internal
945*/
946void QGraphicsViewPrivate::processPendingUpdates()
947{
948 if (!scene)
949 return;
950
951 if (fullUpdatePending) {
952 viewport->update();
953 } else if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) {
954 viewport->update(dirtyBoundingRect);
955 } else {
956 viewport->update(dirtyRegion); // Already adjusted in updateRect/Region.
957 }
958
959 dirtyBoundingRect = QRect();
960 dirtyRegion = QRegion();
961}
962
963static inline bool intersectsViewport(const QRect &r, int width, int height)
964{ return !(r.left() > width) && !(r.right() < 0) && !(r.top() >= height) && !(r.bottom() < 0); }
965
966static inline bool containsViewport(const QRect &r, int width, int height)
967{ return r.left() <= 0 && r.top() <= 0 && r.right() >= width - 1 && r.bottom() >= height - 1; }
968
969static inline void QRect_unite(QRect *rect, const QRect &other)
970{
971 if (rect->isEmpty()) {
972 *rect = other;
973 } else {
974 rect->setCoords(qMin(rect->left(), other.left()), qMin(rect->top(), other.top()),
975 qMax(rect->right(), other.right()), qMax(rect->bottom(), other.bottom()));
976 }
977}
978
979/*
980 Calling this function results in update rects being clipped to the item's
981 bounding rect. Note that updates prior to this function call is not clipped.
982 The clip is removed by passing \nullptr.
983*/
984void QGraphicsViewPrivate::setUpdateClip(QGraphicsItem *item)
985{
986 Q_Q(QGraphicsView);
987 // We simply ignore the request if the update mode is either FullViewportUpdate
988 // or NoViewportUpdate; in that case there's no point in clipping anything.
989 if (!item || viewportUpdateMode == QGraphicsView::NoViewportUpdate
990 || viewportUpdateMode == QGraphicsView::FullViewportUpdate) {
991 hasUpdateClip = false;
992 return;
993 }
994
995 // Calculate the clip (item's bounding rect in view coordinates).
996 // Optimized version of:
997 // QRect clip = item->deviceTransform(q->viewportTransform())
998 // .mapRect(item->boundingRect()).toAlignedRect();
999 QRect clip;
1000 if (item->d_ptr->itemIsUntransformable()) {
1001 QTransform xform = item->deviceTransform(q->viewportTransform());
1002 clip = xform.mapRect(item->boundingRect()).toAlignedRect();
1003 } else if (item->d_ptr->sceneTransformTranslateOnly && identityMatrix) {
1004 QRectF r(item->boundingRect());
1005 r.translate(item->d_ptr->sceneTransform.dx() - horizontalScroll(),
1006 item->d_ptr->sceneTransform.dy() - verticalScroll());
1007 clip = r.toAlignedRect();
1008 } else if (!q->isTransformed()) {
1009 clip = item->d_ptr->sceneTransform.mapRect(item->boundingRect()).toAlignedRect();
1010 } else {
1011 QTransform xform = item->d_ptr->sceneTransform;
1012 xform *= q->viewportTransform();
1013 clip = xform.mapRect(item->boundingRect()).toAlignedRect();
1014 }
1015
1016 if (hasUpdateClip) {
1017 // Intersect with old clip.
1018 updateClip &= clip;
1019 } else {
1020 updateClip = clip;
1021 hasUpdateClip = true;
1022 }
1023}
1024
1025bool QGraphicsViewPrivate::updateRegion(const QRectF &rect, const QTransform &xform)
1026{
1027 if (rect.isEmpty())
1028 return false;
1029
1030 if (viewportUpdateMode != QGraphicsView::MinimalViewportUpdate
1031 && viewportUpdateMode != QGraphicsView::SmartViewportUpdate) {
1032 // No point in updating with QRegion granularity; use the rect instead.
1033 return updateRectF(xform.mapRect(rect));
1034 }
1035
1036 // Update mode is either Minimal or Smart, so we have to do a potentially slow operation,
1037 // which is clearly documented here: QGraphicsItem::setBoundingRegionGranularity.
1038 const QRegion region = xform.map(QRegion(rect.toAlignedRect()));
1039 QRect viewRect = region.boundingRect();
1040 const bool dontAdjustForAntialiasing = optimizationFlags & QGraphicsView::DontAdjustForAntialiasing;
1041 if (dontAdjustForAntialiasing)
1042 viewRect.adjust(-1, -1, 1, 1);
1043 else
1044 viewRect.adjust(-2, -2, 2, 2);
1045 if (!intersectsViewport(viewRect, viewport->width(), viewport->height()))
1046 return false; // Update region for sure outside viewport.
1047
1048 for (QRect viewRect : region) {
1049 if (dontAdjustForAntialiasing)
1050 viewRect.adjust(-1, -1, 1, 1);
1051 else
1052 viewRect.adjust(-2, -2, 2, 2);
1053 if (hasUpdateClip)
1054 viewRect &= updateClip;
1055 dirtyRegion += viewRect;
1056 }
1057
1058 return true;
1059}
1060
1061// NB! Assumes the rect 'r' is already aligned and adjusted for antialiasing.
1062// For QRectF use updateRectF(const QRectF &) to ensure proper adjustments.
1063bool QGraphicsViewPrivate::updateRect(const QRect &r)
1064{
1065 if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate
1066 || !intersectsViewport(r, viewport->width(), viewport->height())) {
1067 return false;
1068 }
1069
1070 switch (viewportUpdateMode) {
1071 case QGraphicsView::FullViewportUpdate:
1072 fullUpdatePending = true;
1073 viewport->update();
1074 break;
1075 case QGraphicsView::BoundingRectViewportUpdate:
1076 if (hasUpdateClip)
1077 QRect_unite(&dirtyBoundingRect, r & updateClip);
1078 else
1079 QRect_unite(&dirtyBoundingRect, r);
1080 if (containsViewport(dirtyBoundingRect, viewport->width(), viewport->height())) {
1081 fullUpdatePending = true;
1082 viewport->update();
1083 }
1084 break;
1085 case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE
1086 case QGraphicsView::MinimalViewportUpdate:
1087 if (hasUpdateClip)
1088 dirtyRegion += r & updateClip;
1089 else
1090 dirtyRegion += r;
1091 break;
1092 default:
1093 break;
1094 }
1095
1096 return true;
1097}
1098
1099QStyleOptionGraphicsItem *QGraphicsViewPrivate::allocStyleOptionsArray(int numItems)
1100{
1101 if (mustAllocateStyleOptions || (numItems > styleOptions.capacity()))
1102 // too many items, let's allocate on-the-fly
1103 return new QStyleOptionGraphicsItem[numItems];
1104
1105 // expand only whenever necessary
1106 if (numItems > styleOptions.size())
1107 styleOptions.resize(numItems);
1108
1109 mustAllocateStyleOptions = true;
1110 return styleOptions.data();
1111}
1112
1113void QGraphicsViewPrivate::freeStyleOptionsArray(QStyleOptionGraphicsItem *array)
1114{
1115 mustAllocateStyleOptions = false;
1116 if (array != styleOptions.data())
1117 delete [] array;
1118}
1119
1120Q_GUI_EXPORT extern QPainterPath qt_regionToPath(const QRegion &region);
1121
1122/*!
1123 \class QGraphicsViewPrivate
1124 \inmodule QtWidgets
1125 \internal
1126*/
1127
1128/*!
1129 ### Adjustments in findItems: mapToScene(QRect) forces us to adjust the
1130 input rectangle by (0, 0, 1, 1), because it uses QRect::bottomRight()
1131 (etc) when mapping the rectangle to a polygon (which is _wrong_). In
1132 addition, as QGraphicsItem::boundingRect() is defined in logical space,
1133 but the default pen for QPainter is cosmetic with a width of 0, QPainter
1134 is at risk of painting 1 pixel outside the bounding rect. Therefore we
1135 must search for items with an adjustment of (-1, -1, 1, 1).
1136*/
1137QList<QGraphicsItem *> QGraphicsViewPrivate::findItems(const QRegion &exposedRegion, bool *allItems,
1138 const QTransform &viewTransform) const
1139{
1140 Q_Q(const QGraphicsView);
1141
1142 // Step 1) If all items are contained within the expose region, then
1143 // return a list of all visible items. ### the scene's growing bounding
1144 // rect does not take into account untransformable items.
1145 const QRectF exposedRegionSceneBounds = q->mapToScene(exposedRegion.boundingRect().adjusted(-1, -1, 1, 1))
1146 .boundingRect();
1147 if (exposedRegionSceneBounds.contains(scene->sceneRect())) {
1148 Q_ASSERT(allItems);
1149 *allItems = true;
1150
1151 // All items are guaranteed within the exposed region.
1152 return scene->items(Qt::AscendingOrder);
1153 }
1154
1155 // Step 2) If the expose region is a simple rect and the view is only
1156 // translated or scaled, search for items using
1157 // QGraphicsScene::items(QRectF).
1158 bool simpleRectLookup = exposedRegion.rectCount() == 1 && matrix.type() <= QTransform::TxScale;
1159 if (simpleRectLookup) {
1160 return scene->items(exposedRegionSceneBounds,
1161 Qt::IntersectsItemBoundingRect,
1162 Qt::AscendingOrder, viewTransform);
1163 }
1164
1165 // If the region is complex or the view has a complex transform, adjust
1166 // the expose region, convert it to a path, and then search for items
1167 // using QGraphicsScene::items(QPainterPath);
1168 QRegion adjustedRegion;
1169 for (const QRect &r : exposedRegion)
1170 adjustedRegion += r.adjusted(-1, -1, 1, 1);
1171
1172 const QPainterPath exposedScenePath(q->mapToScene(qt_regionToPath(adjustedRegion)));
1173 return scene->items(exposedScenePath, Qt::IntersectsItemBoundingRect,
1174 Qt::AscendingOrder, viewTransform);
1175}
1176
1177/*!
1178 \internal
1179
1180 Enables input methods for the view if and only if the current focus item of
1181 the scene accepts input methods. Call function whenever that condition has
1182 potentially changed.
1183*/
1184void QGraphicsViewPrivate::updateInputMethodSensitivity()
1185{
1186 Q_Q(QGraphicsView);
1187 QGraphicsItem *focusItem = nullptr;
1188 bool enabled = scene && (focusItem = scene->focusItem())
1189 && (focusItem->d_ptr->flags & QGraphicsItem::ItemAcceptsInputMethod);
1190 q->setAttribute(Qt::WA_InputMethodEnabled, enabled);
1191 q->viewport()->setAttribute(Qt::WA_InputMethodEnabled, enabled);
1192
1193 if (!enabled) {
1194 q->setInputMethodHints({ });
1195 return;
1196 }
1197
1198 QGraphicsProxyWidget *proxy = focusItem->d_ptr->isWidget && focusItem->d_ptr->isProxyWidget()
1199 ? static_cast<QGraphicsProxyWidget *>(focusItem) : nullptr;
1200 if (!proxy) {
1201 q->setInputMethodHints(focusItem->inputMethodHints());
1202 } else if (QWidget *widget = proxy->widget()) {
1203 if (QWidget *fw = widget->focusWidget())
1204 widget = fw;
1205 q->setInputMethodHints(widget->inputMethodHints());
1206 } else {
1207 q->setInputMethodHints({ });
1208 }
1209}
1210
1211/*!
1212 Constructs a QGraphicsView. \a parent is passed to QWidget's constructor.
1213*/
1214QGraphicsView::QGraphicsView(QWidget *parent)
1215 : QAbstractScrollArea(*new QGraphicsViewPrivate, parent)
1216{
1217 setViewport(nullptr);
1218 setAcceptDrops(true);
1219 setBackgroundRole(QPalette::Base);
1220 // Investigate leaving these disabled by default.
1221 setAttribute(Qt::WA_InputMethodEnabled);
1222 viewport()->setAttribute(Qt::WA_InputMethodEnabled);
1223}
1224
1225/*!
1226 Constructs a QGraphicsView and sets the visualized scene to \a
1227 scene. \a parent is passed to QWidget's constructor.
1228*/
1229QGraphicsView::QGraphicsView(QGraphicsScene *scene, QWidget *parent)
1230 : QAbstractScrollArea(*new QGraphicsViewPrivate, parent)
1231{
1232 setScene(scene);
1233 setViewport(nullptr);
1234 setAcceptDrops(true);
1235 setBackgroundRole(QPalette::Base);
1236 // Investigate leaving these disabled by default.
1237 setAttribute(Qt::WA_InputMethodEnabled);
1238 viewport()->setAttribute(Qt::WA_InputMethodEnabled);
1239}
1240
1241/*!
1242 \internal
1243 */
1244QGraphicsView::QGraphicsView(QGraphicsViewPrivate &dd, QWidget *parent)
1245 : QAbstractScrollArea(dd, parent)
1246{
1247 setViewport(nullptr);
1248 setAcceptDrops(true);
1249 setBackgroundRole(QPalette::Base);
1250 // Investigate leaving these disabled by default.
1251 setAttribute(Qt::WA_InputMethodEnabled);
1252 viewport()->setAttribute(Qt::WA_InputMethodEnabled);
1253}
1254
1255/*!
1256 Destructs the QGraphicsView object.
1257*/
1258QGraphicsView::~QGraphicsView()
1259{
1260 Q_D(QGraphicsView);
1261 if (d->scene)
1262 d->scene->d_func()->views.removeAll(this);
1263 delete d->lastDragDropEvent;
1264}
1265
1266/*!
1267 \reimp
1268*/
1269QSize QGraphicsView::sizeHint() const
1270{
1271 Q_D(const QGraphicsView);
1272 if (d->scene) {
1273 QSizeF baseSize = d->matrix.mapRect(sceneRect()).size();
1274 baseSize += QSizeF(d->frameWidth * 2, d->frameWidth * 2);
1275 return baseSize.boundedTo((3 * QGuiApplication::primaryScreen()->virtualSize()) / 4).toSize();
1276 }
1277 return QAbstractScrollArea::sizeHint();
1278}
1279
1280/*!
1281 \property QGraphicsView::renderHints
1282 \brief the default render hints for the view
1283
1284 These hints are
1285 used to initialize QPainter before each visible item is drawn. QPainter
1286 uses render hints to toggle rendering features such as antialiasing and
1287 smooth pixmap transformation.
1288
1289 QPainter::TextAntialiasing is enabled by default.
1290
1291 Example:
1292
1293 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 1
1294*/
1295QPainter::RenderHints QGraphicsView::renderHints() const
1296{
1297 Q_D(const QGraphicsView);
1298 return d->renderHints;
1299}
1300void QGraphicsView::setRenderHints(QPainter::RenderHints hints)
1301{
1302 Q_D(QGraphicsView);
1303 if (hints == d->renderHints)
1304 return;
1305 d->renderHints = hints;
1306 d->updateAll();
1307}
1308
1309/*!
1310 If \a enabled is true, the render hint \a hint is enabled; otherwise it
1311 is disabled.
1312
1313 \sa renderHints
1314*/
1315void QGraphicsView::setRenderHint(QPainter::RenderHint hint, bool enabled)
1316{
1317 Q_D(QGraphicsView);
1318 QPainter::RenderHints oldHints = d->renderHints;
1319 d->renderHints.setFlag(hint, enabled);
1320 if (oldHints != d->renderHints)
1321 d->updateAll();
1322}
1323
1324/*!
1325 \property QGraphicsView::alignment
1326 \brief the alignment of the scene in the view when the whole
1327 scene is visible.
1328
1329 If the whole scene is visible in the view, (i.e., there are no visible
1330 scroll bars,) the view's alignment will decide where the scene will be
1331 rendered in the view. For example, if the alignment is Qt::AlignCenter,
1332 which is default, the scene will be centered in the view, and if the
1333 alignment is (Qt::AlignLeft | Qt::AlignTop), the scene will be rendered in
1334 the top-left corner of the view.
1335*/
1336Qt::Alignment QGraphicsView::alignment() const
1337{
1338 Q_D(const QGraphicsView);
1339 return d->alignment;
1340}
1341void QGraphicsView::setAlignment(Qt::Alignment alignment)
1342{
1343 Q_D(QGraphicsView);
1344 if (d->alignment != alignment) {
1345 d->alignment = alignment;
1346 d->recalculateContentSize();
1347 }
1348}
1349
1350/*!
1351 \property QGraphicsView::transformationAnchor
1352 \brief how the view should position the scene during transformations.
1353
1354 QGraphicsView uses this property to decide how to position the scene in
1355 the viewport when the transformation matrix changes, and the coordinate
1356 system of the view is transformed. The default behavior, AnchorViewCenter,
1357 ensures that the scene point at the center of the view remains unchanged
1358 during transformations (e.g., when rotating, the scene will appear to
1359 rotate around the center of the view).
1360
1361 Note that the effect of this property is noticeable when only a part of the
1362 scene is visible (i.e., when there are scroll bars). Otherwise, if the
1363 whole scene fits in the view, QGraphicsScene uses the view \l alignment to
1364 position the scene in the view.
1365
1366 \sa alignment, resizeAnchor
1367*/
1368QGraphicsView::ViewportAnchor QGraphicsView::transformationAnchor() const
1369{
1370 Q_D(const QGraphicsView);
1371 return d->transformationAnchor;
1372}
1373void QGraphicsView::setTransformationAnchor(ViewportAnchor anchor)
1374{
1375 Q_D(QGraphicsView);
1376 d->transformationAnchor = anchor;
1377
1378 // Ensure mouse tracking is enabled in the case we are using AnchorUnderMouse
1379 // in order to have up-to-date information for centering the view.
1380 if (d->transformationAnchor == AnchorUnderMouse)
1381 d->viewport->setMouseTracking(true);
1382}
1383
1384/*!
1385 \property QGraphicsView::resizeAnchor
1386 \brief how the view should position the scene when the view is resized.
1387
1388 QGraphicsView uses this property to decide how to position the scene in
1389 the viewport when the viewport widget's size changes. The default
1390 behavior, NoAnchor, leaves the scene's position unchanged during a resize;
1391 the top-left corner of the view will appear to be anchored while resizing.
1392
1393 Note that the effect of this property is noticeable when only a part of the
1394 scene is visible (i.e., when there are scroll bars). Otherwise, if the
1395 whole scene fits in the view, QGraphicsScene uses the view \l alignment to
1396 position the scene in the view.
1397
1398 \sa alignment, transformationAnchor
1399*/
1400QGraphicsView::ViewportAnchor QGraphicsView::resizeAnchor() const
1401{
1402 Q_D(const QGraphicsView);
1403 return d->resizeAnchor;
1404}
1405void QGraphicsView::setResizeAnchor(ViewportAnchor anchor)
1406{
1407 Q_D(QGraphicsView);
1408 d->resizeAnchor = anchor;
1409
1410 // Ensure mouse tracking is enabled in the case we are using AnchorUnderMouse
1411 // in order to have up-to-date information for centering the view.
1412 if (d->resizeAnchor == AnchorUnderMouse)
1413 d->viewport->setMouseTracking(true);
1414}
1415
1416/*!
1417 \property QGraphicsView::viewportUpdateMode
1418 \brief how the viewport should update its contents.
1419
1420 \since 4.3
1421
1422 QGraphicsView uses this property to decide how to update areas of the
1423 scene that have been reexposed or changed. Usually you do not need to
1424 modify this property, but there are some cases where doing so can improve
1425 rendering performance. See the ViewportUpdateMode documentation for
1426 specific details.
1427
1428 The default value is MinimalViewportUpdate, where QGraphicsView will
1429 update as small an area of the viewport as possible when the contents
1430 change.
1431
1432 \sa ViewportUpdateMode, cacheMode
1433*/
1434QGraphicsView::ViewportUpdateMode QGraphicsView::viewportUpdateMode() const
1435{
1436 Q_D(const QGraphicsView);
1437 return d->viewportUpdateMode;
1438}
1439void QGraphicsView::setViewportUpdateMode(ViewportUpdateMode mode)
1440{
1441 Q_D(QGraphicsView);
1442 d->viewportUpdateMode = mode;
1443}
1444
1445/*!
1446 \property QGraphicsView::optimizationFlags
1447 \brief flags that can be used to tune QGraphicsView's performance.
1448
1449 \since 4.3
1450
1451 QGraphicsView uses clipping, extra bounding rect adjustments, and certain
1452 other aids to improve rendering quality and performance for the common
1453 case graphics scene. However, depending on the target platform, the scene,
1454 and the viewport in use, some of these operations can degrade performance.
1455
1456 The effect varies from flag to flag; see the OptimizationFlags
1457 documentation for details.
1458
1459 By default, no optimization flags are enabled.
1460
1461 \sa setOptimizationFlag()
1462*/
1463QGraphicsView::OptimizationFlags QGraphicsView::optimizationFlags() const
1464{
1465 Q_D(const QGraphicsView);
1466 return d->optimizationFlags;
1467}
1468void QGraphicsView::setOptimizationFlags(OptimizationFlags flags)
1469{
1470 Q_D(QGraphicsView);
1471 d->optimizationFlags = flags;
1472}
1473
1474/*!
1475 Enables \a flag if \a enabled is true; otherwise disables \a flag.
1476
1477 \sa optimizationFlags
1478*/
1479void QGraphicsView::setOptimizationFlag(OptimizationFlag flag, bool enabled)
1480{
1481 Q_D(QGraphicsView);
1482 d->optimizationFlags.setFlag(flag, enabled);
1483}
1484
1485/*!
1486 \property QGraphicsView::dragMode
1487 \brief the behavior for dragging the mouse over the scene while
1488 the left mouse button is pressed.
1489
1490 This property defines what should happen when the user clicks on the scene
1491 background and drags the mouse (e.g., scrolling the viewport contents
1492 using a pointing hand cursor, or selecting multiple items with a rubber
1493 band). The default value, NoDrag, does nothing.
1494
1495 This behavior only affects mouse clicks that are not handled by any item.
1496 You can define a custom behavior by creating a subclass of QGraphicsView
1497 and reimplementing mouseMoveEvent().
1498*/
1499QGraphicsView::DragMode QGraphicsView::dragMode() const
1500{
1501 Q_D(const QGraphicsView);
1502 return d->dragMode;
1503}
1504void QGraphicsView::setDragMode(DragMode mode)
1505{
1506 Q_D(QGraphicsView);
1507 if (d->dragMode == mode)
1508 return;
1509
1510#if QT_CONFIG(rubberband)
1511 d->clearRubberBand();
1512#endif
1513
1514#ifndef QT_NO_CURSOR
1515 if (d->dragMode == ScrollHandDrag)
1516 viewport()->unsetCursor();
1517#endif
1518
1519 // If dragMode is unset while dragging, e.g. via a keyEvent, we
1520 // don't unset the handScrolling state. When enabling scrolling
1521 // again the mouseMoveEvent will automatically start scrolling,
1522 // without a mousePress
1523 if (d->dragMode == ScrollHandDrag && mode == NoDrag && d->handScrolling)
1524 d->handScrolling = false;
1525
1526 d->dragMode = mode;
1527
1528#ifndef QT_NO_CURSOR
1529 if (d->dragMode == ScrollHandDrag) {
1530 // Forget the stored viewport cursor when we enter scroll hand drag mode.
1531 d->hasStoredOriginalCursor = false;
1532 viewport()->setCursor(Qt::OpenHandCursor);
1533 }
1534#endif
1535}
1536
1537#if QT_CONFIG(rubberband)
1538/*!
1539 \property QGraphicsView::rubberBandSelectionMode
1540 \brief the behavior for selecting items with a rubber band selection rectangle.
1541 \since 4.3
1542
1543 This property defines how items are selected when using the RubberBandDrag
1544 drag mode.
1545
1546 The default value is Qt::IntersectsItemShape; all items whose shape
1547 intersects with or is contained by the rubber band are selected.
1548
1549 \sa dragMode, items(), rubberBandRect()
1550*/
1551Qt::ItemSelectionMode QGraphicsView::rubberBandSelectionMode() const
1552{
1553 Q_D(const QGraphicsView);
1554 return d->rubberBandSelectionMode;
1555}
1556void QGraphicsView::setRubberBandSelectionMode(Qt::ItemSelectionMode mode)
1557{
1558 Q_D(QGraphicsView);
1559 d->rubberBandSelectionMode = mode;
1560}
1561
1562/*!
1563 \since 5.1
1564 This functions returns the current rubber band area (in viewport coordinates) if the user
1565 is currently doing an itemselection with rubber band. When the user is not using the
1566 rubber band this functions returns (a null) QRectF().
1567
1568 Notice that part of this QRect can be outside the visual viewport. It can e.g
1569 contain negative values.
1570
1571 \sa rubberBandSelectionMode, rubberBandChanged()
1572*/
1573
1574QRect QGraphicsView::rubberBandRect() const
1575{
1576 Q_D(const QGraphicsView);
1577 if (d->dragMode != QGraphicsView::RubberBandDrag || !d->sceneInteractionAllowed || !d->rubberBanding)
1578 return QRect();
1579
1580 return d->rubberBandRect;
1581}
1582#endif
1583
1584/*!
1585 \property QGraphicsView::cacheMode
1586 \brief which parts of the view are cached
1587
1588 QGraphicsView can cache pre-rendered content in a QPixmap, which is then
1589 drawn onto the viewport. The purpose of such caching is to speed up the
1590 total rendering time for areas that are slow to render. Texture, gradient
1591 and alpha blended backgrounds, for example, can be notibly slow to render;
1592 especially with a transformed view. The CacheBackground flag enables
1593 caching of the view's background. For example:
1594
1595 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 2
1596
1597 The cache is invalidated every time the view is transformed. However, when
1598 scrolling, only partial invalidation is required.
1599
1600 By default, nothing is cached.
1601
1602 \sa resetCachedContent(), QPixmapCache
1603*/
1604QGraphicsView::CacheMode QGraphicsView::cacheMode() const
1605{
1606 Q_D(const QGraphicsView);
1607 return d->cacheMode;
1608}
1609void QGraphicsView::setCacheMode(CacheMode mode)
1610{
1611 Q_D(QGraphicsView);
1612 if (mode == d->cacheMode)
1613 return;
1614 d->cacheMode = mode;
1615 resetCachedContent();
1616}
1617
1618/*!
1619 Resets any cached content. Calling this function will clear
1620 QGraphicsView's cache. If the current cache mode is \l CacheNone, this
1621 function does nothing.
1622
1623 This function is called automatically for you when the backgroundBrush or
1624 QGraphicsScene::backgroundBrush properties change; you only need to call
1625 this function if you have reimplemented QGraphicsScene::drawBackground()
1626 or QGraphicsView::drawBackground() to draw a custom background, and need
1627 to trigger a full redraw.
1628
1629 \sa cacheMode()
1630*/
1631void QGraphicsView::resetCachedContent()
1632{
1633 Q_D(QGraphicsView);
1634 if (d->cacheMode == CacheNone)
1635 return;
1636
1637 if (d->cacheMode & CacheBackground) {
1638 // Background caching is enabled.
1639 d->mustResizeBackgroundPixmap = true;
1640 d->updateAll();
1641 } else if (d->mustResizeBackgroundPixmap) {
1642 // Background caching is disabled.
1643 // Cleanup, free some resources.
1644 d->mustResizeBackgroundPixmap = false;
1645 d->backgroundPixmap = QPixmap();
1646 d->backgroundPixmapExposed = QRegion();
1647 }
1648}
1649
1650/*!
1651 Invalidates and schedules a redraw of \a layers inside \a rect. \a rect is
1652 in scene coordinates. Any cached content for \a layers inside \a rect is
1653 unconditionally invalidated and redrawn.
1654
1655 You can call this function to notify QGraphicsView of changes to the
1656 background or the foreground of the scene. It is commonly used for scenes
1657 with tile-based backgrounds to notify changes when QGraphicsView has
1658 enabled background caching.
1659
1660 Note that QGraphicsView currently supports background caching only (see
1661 QGraphicsView::CacheBackground). This function is equivalent to calling update() if any
1662 layer but QGraphicsScene::BackgroundLayer is passed.
1663
1664 \sa QGraphicsScene::invalidate(), update()
1665*/
1666void QGraphicsView::invalidateScene(const QRectF &rect, QGraphicsScene::SceneLayers layers)
1667{
1668 Q_D(QGraphicsView);
1669 if ((layers & QGraphicsScene::BackgroundLayer) && !d->mustResizeBackgroundPixmap) {
1670 QRect viewRect = mapFromScene(rect).boundingRect();
1671 if (viewport()->rect().intersects(viewRect)) {
1672 // The updated background area is exposed; schedule this area for
1673 // redrawing.
1674 d->backgroundPixmapExposed += viewRect;
1675 if (d->scene)
1676 d->scene->update(rect);
1677 }
1678 }
1679}
1680
1681/*!
1682 \property QGraphicsView::interactive
1683 \brief whether the view allows scene interaction.
1684
1685 If enabled, this view is set to allow scene interaction. Otherwise, this
1686 view will not allow interaction, and any mouse or key events are ignored
1687 (i.e., it will act as a read-only view).
1688
1689 By default, this property is \c true.
1690*/
1691bool QGraphicsView::isInteractive() const
1692{
1693 Q_D(const QGraphicsView);
1694 return d->sceneInteractionAllowed;
1695}
1696void QGraphicsView::setInteractive(bool allowed)
1697{
1698 Q_D(QGraphicsView);
1699 d->sceneInteractionAllowed = allowed;
1700}
1701
1702/*!
1703 Returns a pointer to the scene that is currently visualized in the
1704 view. If no scene is currently visualized, \nullptr is returned.
1705
1706 \sa setScene()
1707*/
1708QGraphicsScene *QGraphicsView::scene() const
1709{
1710 Q_D(const QGraphicsView);
1711 return d->scene;
1712}
1713
1714/*!
1715 Sets the current scene to \a scene. If \a scene is already being
1716 viewed, this function does nothing.
1717
1718 When a scene is set on a view, the QGraphicsScene::changed() signal
1719 is automatically connected to this view's updateScene() slot, and the
1720 view's scroll bars are adjusted to fit the size of the scene.
1721
1722 The view does not take ownership of \a scene.
1723*/
1724void QGraphicsView::setScene(QGraphicsScene *scene)
1725{
1726 Q_D(QGraphicsView);
1727 if (d->scene == scene)
1728 return;
1729
1730 // Always update the viewport when the scene changes.
1731 d->updateAll();
1732
1733 // Remove the previously assigned scene.
1734 if (d->scene) {
1735 disconnect(d->scene, SIGNAL(changed(QList<QRectF>)),
1736 this, SLOT(updateScene(QList<QRectF>)));
1737 disconnect(d->scene, SIGNAL(sceneRectChanged(QRectF)),
1738 this, SLOT(updateSceneRect(QRectF)));
1739 d->scene->d_func()->removeView(this);
1740 d->connectedToScene = false;
1741
1742 if (isActiveWindow() && isVisible()) {
1743 QEvent windowDeactivate(QEvent::WindowDeactivate);
1744 QCoreApplication::sendEvent(d->scene, &windowDeactivate);
1745 }
1746 if (hasFocus())
1747 d->scene->clearFocus();
1748 }
1749
1750 // Assign the new scene and update the contents (scrollbars, etc.)).
1751 if ((d->scene = scene)) {
1752 connect(d->scene, SIGNAL(sceneRectChanged(QRectF)),
1753 this, SLOT(updateSceneRect(QRectF)));
1754 d->updateSceneSlotReimplementedChecked = false;
1755 d->scene->d_func()->addView(this);
1756 d->recalculateContentSize();
1757 d->lastCenterPoint = sceneRect().center();
1758 d->keepLastCenterPoint = true;
1759 // We are only interested in mouse tracking if items accept
1760 // hover events or use non-default cursors.
1761 if (!d->scene->d_func()->allItemsIgnoreHoverEvents
1762 || !d->scene->d_func()->allItemsUseDefaultCursor) {
1763 d->viewport->setMouseTracking(true);
1764 }
1765
1766 // enable touch events if any items is interested in them
1767 if (!d->scene->d_func()->allItemsIgnoreTouchEvents)
1768 d->viewport->setAttribute(Qt::WA_AcceptTouchEvents);
1769
1770 if (isActiveWindow() && isVisible()) {
1771 QEvent windowActivate(QEvent::WindowActivate);
1772 QCoreApplication::sendEvent(d->scene, &windowActivate);
1773 }
1774 } else {
1775 d->recalculateContentSize();
1776 }
1777
1778 d->updateInputMethodSensitivity();
1779
1780 if (d->scene && hasFocus())
1781 d->scene->setFocus();
1782}
1783
1784/*!
1785 \property QGraphicsView::sceneRect
1786 \brief the area of the scene visualized by this view.
1787
1788 The scene rectangle defines the extent of the scene, and in the view's case,
1789 this means the area of the scene that you can navigate using the scroll
1790 bars.
1791
1792 If unset, or if a null QRectF is set, this property has the same value as
1793 QGraphicsScene::sceneRect, and it changes with
1794 QGraphicsScene::sceneRect. Otherwise, the view's scene rect is unaffected
1795 by the scene.
1796
1797 Note that, although the scene supports a virtually unlimited size, the
1798 range of the scroll bars will never exceed the range of an integer
1799 (INT_MIN, INT_MAX). When the scene is larger than the scroll bars' values,
1800 you can choose to use translate() to navigate the scene instead.
1801
1802 By default, this property contains a rectangle at the origin with zero
1803 width and height.
1804
1805 \sa QGraphicsScene::sceneRect
1806*/
1807QRectF QGraphicsView::sceneRect() const
1808{
1809 Q_D(const QGraphicsView);
1810 if (d->hasSceneRect)
1811 return d->sceneRect;
1812 if (d->scene)
1813 return d->scene->sceneRect();
1814 return QRectF();
1815}
1816void QGraphicsView::setSceneRect(const QRectF &rect)
1817{
1818 Q_D(QGraphicsView);
1819 d->hasSceneRect = !rect.isNull();
1820 d->sceneRect = rect;
1821 d->recalculateContentSize();
1822}
1823
1824/*!
1825 Rotates the current view transformation \a angle degrees clockwise.
1826
1827 \sa setTransform(), transform(), scale(), shear(), translate()
1828*/
1829void QGraphicsView::rotate(qreal angle)
1830{
1831 Q_D(QGraphicsView);
1832 QTransform matrix = d->matrix;
1833 matrix.rotate(angle);
1834 setTransform(matrix);
1835}
1836
1837/*!
1838 Scales the current view transformation by (\a sx, \a sy).
1839
1840 \sa setTransform(), transform(), rotate(), shear(), translate()
1841*/
1842void QGraphicsView::scale(qreal sx, qreal sy)
1843{
1844 Q_D(QGraphicsView);
1845 QTransform matrix = d->matrix;
1846 matrix.scale(sx, sy);
1847 setTransform(matrix);
1848}
1849
1850/*!
1851 Shears the current view transformation by (\a sh, \a sv).
1852
1853 \sa setTransform(), transform(), rotate(), scale(), translate()
1854*/
1855void QGraphicsView::shear(qreal sh, qreal sv)
1856{
1857 Q_D(QGraphicsView);
1858 QTransform matrix = d->matrix;
1859 matrix.shear(sh, sv);
1860 setTransform(matrix);
1861}
1862
1863/*!
1864 Translates the current view transformation by (\a dx, \a dy).
1865
1866 \sa setTransform(), transform(), rotate(), shear()
1867*/
1868void QGraphicsView::translate(qreal dx, qreal dy)
1869{
1870 Q_D(QGraphicsView);
1871 QTransform matrix = d->matrix;
1872 matrix.translate(dx, dy);
1873 setTransform(matrix);
1874}
1875
1876/*!
1877 Scrolls the contents of the viewport to ensure that the scene
1878 coordinate \a pos, is centered in the view.
1879
1880 Because \a pos is a floating point coordinate, and the scroll bars operate
1881 on integer coordinates, the centering is only an approximation.
1882
1883 \note If the item is close to or outside the border, it will be visible
1884 in the view, but not centered.
1885
1886 \sa ensureVisible()
1887*/
1888void QGraphicsView::centerOn(const QPointF &pos)
1889{
1890 Q_D(QGraphicsView);
1891 qreal width = viewport()->width();
1892 qreal height = viewport()->height();
1893 QPointF viewPoint = d->matrix.map(pos);
1894 QPointF oldCenterPoint = pos;
1895
1896 if (!d->leftIndent) {
1897 if (isRightToLeft()) {
1898 qint64 horizontal = 0;
1899 horizontal += horizontalScrollBar()->minimum();
1900 horizontal += horizontalScrollBar()->maximum();
1901 horizontal -= qRound(viewPoint.x() - width / 2.0);
1902 horizontalScrollBar()->setValue(horizontal);
1903 } else {
1904 horizontalScrollBar()->setValue(qRound(viewPoint.x() - width / 2.0));
1905 }
1906 }
1907 if (!d->topIndent)
1908 verticalScrollBar()->setValue(qRound(viewPoint.y() - height / 2.0));
1909 d->lastCenterPoint = oldCenterPoint;
1910}
1911
1912/*!
1913 \fn QGraphicsView::centerOn(qreal x, qreal y)
1914 \overload
1915
1916 This function is provided for convenience. It's equivalent to calling
1917 centerOn(QPointF(\a x, \a y)).
1918*/
1919
1920/*!
1921 \overload
1922
1923 Scrolls the contents of the viewport to ensure that \a item
1924 is centered in the view.
1925
1926 \sa ensureVisible()
1927*/
1928void QGraphicsView::centerOn(const QGraphicsItem *item)
1929{
1930 centerOn(item->sceneBoundingRect().center());
1931}
1932
1933/*!
1934 Scrolls the contents of the viewport so that the scene rectangle \a rect
1935 is visible, with margins specified in pixels by \a xmargin and \a
1936 ymargin. If the specified rect cannot be reached, the contents are
1937 scrolled to the nearest valid position. The default value for both margins
1938 is 50 pixels.
1939
1940 \sa centerOn()
1941*/
1942void QGraphicsView::ensureVisible(const QRectF &rect, int xmargin, int ymargin)
1943{
1944 Q_D(QGraphicsView);
1945 qreal width = viewport()->width();
1946 qreal height = viewport()->height();
1947 QRectF viewRect = d->matrix.mapRect(rect);
1948
1949 qreal left = d->horizontalScroll();
1950 qreal right = left + width;
1951 qreal top = d->verticalScroll();
1952 qreal bottom = top + height;
1953
1954 if (viewRect.left() <= left + xmargin) {
1955 // need to scroll from the left
1956 if (!d->leftIndent)
1957 horizontalScrollBar()->setValue(int(viewRect.left() - xmargin - 0.5));
1958 }
1959 if (viewRect.right() >= right - xmargin) {
1960 // need to scroll from the right
1961 if (!d->leftIndent)
1962 horizontalScrollBar()->setValue(int(viewRect.right() - width + xmargin + 0.5));
1963 }
1964 if (viewRect.top() <= top + ymargin) {
1965 // need to scroll from the top
1966 if (!d->topIndent)
1967 verticalScrollBar()->setValue(int(viewRect.top() - ymargin - 0.5));
1968 }
1969 if (viewRect.bottom() >= bottom - ymargin) {
1970 // need to scroll from the bottom
1971 if (!d->topIndent)
1972 verticalScrollBar()->setValue(int(viewRect.bottom() - height + ymargin + 0.5));
1973 }
1974}
1975
1976/*!
1977 \fn QGraphicsView::ensureVisible(qreal x, qreal y, qreal w, qreal h,
1978 int xmargin, int ymargin)
1979 \overload
1980
1981 This function is provided for convenience. It's equivalent to calling
1982 ensureVisible(QRectF(\a x, \a y, \a w, \a h), \a xmargin, \a ymargin).
1983*/
1984
1985/*!
1986 \overload
1987
1988 Scrolls the contents of the viewport so that the center of item \a item is
1989 visible, with margins specified in pixels by \a xmargin and \a ymargin. If
1990 the specified point cannot be reached, the contents are scrolled to the
1991 nearest valid position. The default value for both margins is 50 pixels.
1992
1993 \sa centerOn()
1994*/
1995void QGraphicsView::ensureVisible(const QGraphicsItem *item, int xmargin, int ymargin)
1996{
1997 ensureVisible(item->sceneBoundingRect(), xmargin, ymargin);
1998}
1999
2000/*!
2001 Scales the view matrix and scrolls the scroll bars to ensure that the
2002 scene rectangle \a rect fits inside the viewport. \a rect must be inside
2003 the scene rect; otherwise, fitInView() cannot guarantee that the whole
2004 rect is visible.
2005
2006 This function keeps the view's rotation, translation, or shear. The view
2007 is scaled according to \a aspectRatioMode. \a rect will be centered in the
2008 view if it does not fit tightly.
2009
2010 It's common to call fitInView() from inside a reimplementation of
2011 resizeEvent(), to ensure that the whole scene, or parts of the scene,
2012 scales automatically to fit the new size of the viewport as the view is
2013 resized. Note though, that calling fitInView() from inside resizeEvent()
2014 can lead to unwanted resize recursion, if the new transformation toggles
2015 the automatic state of the scrollbars. You can toggle the scrollbar
2016 policies to always on or always off to prevent this (see
2017 horizontalScrollBarPolicy() and verticalScrollBarPolicy()).
2018
2019 If \a rect is empty, or if the viewport is too small, this
2020 function will do nothing.
2021
2022 \sa setTransform(), ensureVisible(), centerOn()
2023*/
2024void QGraphicsView::fitInView(const QRectF &rect, Qt::AspectRatioMode aspectRatioMode)
2025{
2026 Q_D(QGraphicsView);
2027 if (!d->scene || rect.isNull())
2028 return;
2029
2030 // Reset the view scale to 1:1.
2031 QRectF unity = d->matrix.mapRect(QRectF(0, 0, 1, 1));
2032 if (unity.isEmpty())
2033 return;
2034 scale(1 / unity.width(), 1 / unity.height());
2035
2036 // Find the ideal x / y scaling ratio to fit \a rect in the view.
2037 int margin = 2;
2038 QRectF viewRect = viewport()->rect().adjusted(margin, margin, -margin, -margin);
2039 if (viewRect.isEmpty())
2040 return;
2041 QRectF sceneRect = d->matrix.mapRect(rect);
2042 if (sceneRect.isEmpty())
2043 return;
2044 qreal xratio = viewRect.width() / sceneRect.width();
2045 qreal yratio = viewRect.height() / sceneRect.height();
2046
2047 // Respect the aspect ratio mode.
2048 switch (aspectRatioMode) {
2049 case Qt::KeepAspectRatio:
2050 xratio = yratio = qMin(xratio, yratio);
2051 break;
2052 case Qt::KeepAspectRatioByExpanding:
2053 xratio = yratio = qMax(xratio, yratio);
2054 break;
2055 case Qt::IgnoreAspectRatio:
2056 break;
2057 }
2058
2059 // Scale and center on the center of \a rect.
2060 scale(xratio, yratio);
2061 centerOn(rect.center());
2062}
2063
2064/*!
2065 \fn void QGraphicsView::fitInView(qreal x, qreal y, qreal w, qreal h,
2066 Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio)
2067
2068 \overload
2069
2070 This convenience function is equivalent to calling
2071 fitInView(QRectF(\a x, \a y, \a w, \a h), \a aspectRatioMode).
2072
2073 \sa ensureVisible(), centerOn()
2074*/
2075
2076/*!
2077 \overload
2078
2079 Ensures that \a item fits tightly inside the view, scaling the view
2080 according to \a aspectRatioMode.
2081
2082 \sa ensureVisible(), centerOn()
2083*/
2084void QGraphicsView::fitInView(const QGraphicsItem *item, Qt::AspectRatioMode aspectRatioMode)
2085{
2086 QPainterPath path = item->isClipped() ? item->clipPath() : item->shape();
2087 if (item->d_ptr->hasTranslateOnlySceneTransform()) {
2088 path.translate(item->d_ptr->sceneTransform.dx(), item->d_ptr->sceneTransform.dy());
2089 fitInView(path.boundingRect(), aspectRatioMode);
2090 } else {
2091 fitInView(item->d_ptr->sceneTransform.map(path).boundingRect(), aspectRatioMode);
2092 }
2093}
2094
2095/*!
2096 Renders the \a source rect, which is in view coordinates, from the scene
2097 into \a target, which is in paint device coordinates, using \a
2098 painter. This function is useful for capturing the contents of the view
2099 onto a paint device, such as a QImage (e.g., to take a screenshot), or for
2100 printing to QPrinter. For example:
2101
2102 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 4
2103
2104 If \a source is a null rect, this function will use viewport()->rect() to
2105 determine what to draw. If \a target is a null rect, the full dimensions
2106 of \a painter's paint device (e.g., for a QPrinter, the page size) will be
2107 used.
2108
2109 The source rect contents will be transformed according to \a
2110 aspectRatioMode to fit into the target rect. By default, the aspect ratio
2111 is kept, and \a source is scaled to fit in \a target.
2112
2113 \sa QGraphicsScene::render()
2114*/
2115void QGraphicsView::render(QPainter *painter, const QRectF &target, const QRect &source,
2116 Qt::AspectRatioMode aspectRatioMode)
2117{
2118 // ### Switch to using the recursive rendering algorithm instead.
2119
2120 Q_D(QGraphicsView);
2121 if (!d->scene || !(painter && painter->isActive()))
2122 return;
2123
2124 // Default source rect = viewport rect
2125 QRect sourceRect = source;
2126 if (source.isNull())
2127 sourceRect = viewport()->rect();
2128
2129 // Default target rect = device rect
2130 QRectF targetRect = target;
2131 if (target.isNull()) {
2132 if (painter->device()->devType() == QInternal::Picture)
2133 targetRect = sourceRect;
2134 else
2135 targetRect.setRect(0, 0, painter->device()->width(), painter->device()->height());
2136 }
2137
2138 // Find the ideal x / y scaling ratio to fit \a source into \a target.
2139 qreal xratio = targetRect.width() / sourceRect.width();
2140 qreal yratio = targetRect.height() / sourceRect.height();
2141
2142 // Scale according to the aspect ratio mode.
2143 switch (aspectRatioMode) {
2144 case Qt::KeepAspectRatio:
2145 xratio = yratio = qMin(xratio, yratio);
2146 break;
2147 case Qt::KeepAspectRatioByExpanding:
2148 xratio = yratio = qMax(xratio, yratio);
2149 break;
2150 case Qt::IgnoreAspectRatio:
2151 break;
2152 }
2153
2154 // Find all items to draw, and reverse the list (we want to draw
2155 // in reverse order).
2156 QPolygonF sourceScenePoly = mapToScene(sourceRect.adjusted(-1, -1, 1, 1));
2157 QList<QGraphicsItem *> itemList = d->scene->items(sourceScenePoly,
2158 Qt::IntersectsItemBoundingRect);
2159 QGraphicsItem **itemArray = new QGraphicsItem *[itemList.size()];
2160 int numItems = itemList.size();
2161 for (int i = 0; i < numItems; ++i)
2162 itemArray[numItems - i - 1] = itemList.at(i);
2163 itemList.clear();
2164
2165 // Setup painter matrix.
2166 QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
2167 QTransform painterMatrix = d->matrix * moveMatrix;
2168 painterMatrix *= QTransform()
2169 .translate(targetRect.left(), targetRect.top())
2170 .scale(xratio, yratio)
2171 .translate(-sourceRect.left(), -sourceRect.top());
2172
2173 // Generate the style options
2174 QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
2175 for (int i = 0; i < numItems; ++i)
2176 itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], painterMatrix, targetRect.toRect());
2177
2178 painter->save();
2179
2180 // Clip in device coordinates to avoid QRegion transformations.
2181 painter->setClipRect(targetRect);
2182 QPainterPath path;
2183 path.addPolygon(sourceScenePoly);
2184 path.closeSubpath();
2185 painter->setClipPath(painterMatrix.map(path), Qt::IntersectClip);
2186
2187 // Transform the painter.
2188 painter->setTransform(painterMatrix, true);
2189
2190 // Render the scene.
2191 QRectF sourceSceneRect = sourceScenePoly.boundingRect();
2192 drawBackground(painter, sourceSceneRect);
2193 drawItems(painter, numItems, itemArray, styleOptionArray);
2194 drawForeground(painter, sourceSceneRect);
2195
2196 delete [] itemArray;
2197 d->freeStyleOptionsArray(styleOptionArray);
2198
2199 painter->restore();
2200}
2201
2202/*!
2203 Returns a list of all the items in the associated scene, in descending
2204 stacking order (i.e., the first item in the returned list is the uppermost
2205 item).
2206
2207 \sa QGraphicsScene::items(), {QGraphicsItem#Sorting}{Sorting}
2208*/
2209QList<QGraphicsItem *> QGraphicsView::items() const
2210{
2211 Q_D(const QGraphicsView);
2212 if (!d->scene)
2213 return QList<QGraphicsItem *>();
2214 return d->scene->items();
2215}
2216
2217/*!
2218 Returns a list of all the items at the position \a pos in the view. The
2219 items are listed in descending stacking order (i.e., the first item in the
2220 list is the uppermost item, and the last item is the lowermost item). \a
2221 pos is in viewport coordinates.
2222
2223 This function is most commonly called from within mouse event handlers in
2224 a subclass in QGraphicsView. \a pos is in untransformed viewport
2225 coordinates, just like QMouseEvent::position().
2226
2227 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 5_6_declaration
2228 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 5
2229 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 5_6_end
2230
2231 \sa QGraphicsScene::items(), {QGraphicsItem#Sorting}{Sorting}
2232*/
2233QList<QGraphicsItem *> QGraphicsView::items(const QPoint &pos) const
2234{
2235 Q_D(const QGraphicsView);
2236 if (!d->scene)
2237 return QList<QGraphicsItem *>();
2238 // ### Unify these two, and use the items(QPointF) version in
2239 // QGraphicsScene instead. The scene items function could use the viewport
2240 // transform to map the point to a rect/polygon.
2241 if ((d->identityMatrix || d->matrix.type() <= QTransform::TxScale)) {
2242 // Use the rect version
2243 QTransform xinv = viewportTransform().inverted();
2244 return d->scene->items(xinv.mapRect(QRectF(pos.x(), pos.y(), 1, 1)),
2245 Qt::IntersectsItemShape,
2246 Qt::DescendingOrder,
2247 viewportTransform());
2248 }
2249 // Use the polygon version
2250 return d->scene->items(mapToScene(pos.x(), pos.y(), 1, 1),
2251 Qt::IntersectsItemShape,
2252 Qt::DescendingOrder,
2253 viewportTransform());
2254}
2255
2256/*!
2257 \fn QGraphicsView::items(int x, int y) const
2258
2259 This function is provided for convenience. It's equivalent to calling
2260 items(QPoint(\a x, \a y)).
2261*/
2262
2263/*!
2264 \overload
2265
2266 Returns a list of all the items that, depending on \a mode, are either
2267 contained by or intersect with \a rect. \a rect is in viewport
2268 coordinates.
2269
2270 The default value for \a mode is Qt::IntersectsItemShape; all items whose
2271 exact shape intersects with or is contained by \a rect are returned.
2272
2273 The items are sorted in descending stacking order (i.e., the first item in
2274 the returned list is the uppermost item).
2275
2276 \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
2277*/
2278QList<QGraphicsItem *> QGraphicsView::items(const QRect &rect, Qt::ItemSelectionMode mode) const
2279{
2280 Q_D(const QGraphicsView);
2281 if (!d->scene)
2282 return QList<QGraphicsItem *>();
2283 return d->scene->items(mapToScene(rect), mode, Qt::DescendingOrder, viewportTransform());
2284}
2285
2286/*!
2287 \fn QList<QGraphicsItem *> QGraphicsView::items(int x, int y, int w, int h, Qt::ItemSelectionMode mode) const
2288 \since 4.3
2289
2290 This convenience function is equivalent to calling items(QRectF(\a x, \a
2291 y, \a w, \a h), \a mode).
2292*/
2293
2294/*!
2295 \overload
2296
2297 Returns a list of all the items that, depending on \a mode, are either
2298 contained by or intersect with \a polygon. \a polygon is in viewport
2299 coordinates.
2300
2301 The default value for \a mode is Qt::IntersectsItemShape; all items whose
2302 exact shape intersects with or is contained by \a polygon are returned.
2303
2304 The items are sorted by descending stacking order (i.e., the first item in
2305 the returned list is the uppermost item).
2306
2307 \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
2308*/
2309QList<QGraphicsItem *> QGraphicsView::items(const QPolygon &polygon, Qt::ItemSelectionMode mode) const
2310{
2311 Q_D(const QGraphicsView);
2312 if (!d->scene)
2313 return QList<QGraphicsItem *>();
2314 return d->scene->items(mapToScene(polygon), mode, Qt::DescendingOrder, viewportTransform());
2315}
2316
2317/*!
2318 \overload
2319
2320 Returns a list of all the items that, depending on \a mode, are either
2321 contained by or intersect with \a path. \a path is in viewport
2322 coordinates.
2323
2324 The default value for \a mode is Qt::IntersectsItemShape; all items whose
2325 exact shape intersects with or is contained by \a path are returned.
2326
2327 \sa itemAt(), items(), mapToScene(), {QGraphicsItem#Sorting}{Sorting}
2328*/
2329QList<QGraphicsItem *> QGraphicsView::items(const QPainterPath &path, Qt::ItemSelectionMode mode) const
2330{
2331 Q_D(const QGraphicsView);
2332 if (!d->scene)
2333 return QList<QGraphicsItem *>();
2334 return d->scene->items(mapToScene(path), mode, Qt::DescendingOrder, viewportTransform());
2335}
2336
2337/*!
2338 Returns the item at position \a pos, which is in viewport coordinates.
2339 If there are several items at this position, this function returns
2340 the topmost item.
2341
2342 Example:
2343
2344 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 5_6_declaration
2345 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 6
2346 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 5_6_end
2347
2348 \sa items(), {QGraphicsItem#Sorting}{Sorting}
2349*/
2350QGraphicsItem *QGraphicsView::itemAt(const QPoint &pos) const
2351{
2352 Q_D(const QGraphicsView);
2353 if (!d->scene)
2354 return nullptr;
2355 const QList<QGraphicsItem *> itemsAtPos = items(pos);
2356 return itemsAtPos.isEmpty() ? nullptr : itemsAtPos.first();
2357}
2358
2359/*!
2360 \overload
2361 \fn QGraphicsItem *QGraphicsView::itemAt(int x, int y) const
2362
2363 This function is provided for convenience. It's equivalent to
2364 calling itemAt(QPoint(\a x, \a y)).
2365*/
2366
2367/*!
2368 Returns the viewport coordinate \a point mapped to scene coordinates.
2369
2370 Note: It can be useful to map the whole rectangle covered by the pixel at
2371 \a point instead of the point itself. To do this, you can call
2372 mapToScene(QRect(\a point, QSize(2, 2))).
2373
2374 \sa mapFromScene()
2375*/
2376QPointF QGraphicsView::mapToScene(const QPoint &point) const
2377{
2378 Q_D(const QGraphicsView);
2379 QPointF p = point;
2380 p.rx() += d->horizontalScroll();
2381 p.ry() += d->verticalScroll();
2382 return d->identityMatrix ? p : d->matrix.inverted().map(p);
2383}
2384
2385/*!
2386 \fn QGraphicsView::mapToScene(int x, int y) const
2387
2388 This function is provided for convenience. It's equivalent to calling
2389 mapToScene(QPoint(\a x, \a y)).
2390*/
2391
2392/*!
2393 Returns the viewport rectangle \a rect mapped to a scene coordinate
2394 polygon.
2395
2396 \sa mapFromScene()
2397*/
2398QPolygonF QGraphicsView::mapToScene(const QRect &rect) const
2399{
2400 Q_D(const QGraphicsView);
2401 if (!rect.isValid())
2402 return QPolygonF();
2403
2404 QPointF scrollOffset(d->horizontalScroll(), d->verticalScroll());
2405 QRect r = rect.adjusted(0, 0, 1, 1);
2406 QPointF tl = scrollOffset + r.topLeft();
2407 QPointF tr = scrollOffset + r.topRight();
2408 QPointF br = scrollOffset + r.bottomRight();
2409 QPointF bl = scrollOffset + r.bottomLeft();
2410
2411 QPolygonF poly(4);
2412 if (!d->identityMatrix) {
2413 QTransform x = d->matrix.inverted();
2414 poly[0] = x.map(tl);
2415 poly[1] = x.map(tr);
2416 poly[2] = x.map(br);
2417 poly[3] = x.map(bl);
2418 } else {
2419 poly[0] = tl;
2420 poly[1] = tr;
2421 poly[2] = br;
2422 poly[3] = bl;
2423 }
2424 return poly;
2425}
2426
2427/*!
2428 \fn QGraphicsView::mapToScene(int x, int y, int w, int h) const
2429
2430 This function is provided for convenience. It's equivalent to calling
2431 mapToScene(QRect(\a x, \a y, \a w, \a h)).
2432*/
2433
2434/*!
2435 Returns the viewport polygon \a polygon mapped to a scene coordinate
2436 polygon.
2437
2438 \sa mapFromScene()
2439*/
2440QPolygonF QGraphicsView::mapToScene(const QPolygon &polygon) const
2441{
2442 QPolygonF poly;
2443 poly.reserve(polygon.size());
2444 for (const QPoint &point : polygon)
2445 poly << mapToScene(point);
2446 return poly;
2447}
2448
2449/*!
2450 Returns the viewport painter path \a path mapped to a scene coordinate
2451 painter path.
2452
2453 \sa mapFromScene()
2454*/
2455QPainterPath QGraphicsView::mapToScene(const QPainterPath &path) const
2456{
2457 Q_D(const QGraphicsView);
2458 QTransform matrix = QTransform::fromTranslate(d->horizontalScroll(), d->verticalScroll());
2459 matrix *= d->matrix.inverted();
2460 return matrix.map(path);
2461}
2462
2463/*!
2464 Returns the scene coordinate \a point to viewport coordinates.
2465
2466 \sa mapToScene()
2467*/
2468QPoint QGraphicsView::mapFromScene(const QPointF &point) const
2469{
2470 Q_D(const QGraphicsView);
2471 QPointF p = d->identityMatrix ? point : d->matrix.map(point);
2472 p.rx() -= d->horizontalScroll();
2473 p.ry() -= d->verticalScroll();
2474 return p.toPoint();
2475}
2476
2477/*!
2478 \fn QGraphicsView::mapFromScene(qreal x, qreal y) const
2479
2480 This function is provided for convenience. It's equivalent to
2481 calling mapFromScene(QPointF(\a x, \a y)).
2482*/
2483
2484/*!
2485 Returns the scene rectangle \a rect to a viewport coordinate
2486 polygon.
2487
2488 \sa mapToScene()
2489*/
2490QPolygon QGraphicsView::mapFromScene(const QRectF &rect) const
2491{
2492 Q_D(const QGraphicsView);
2493 QPointF tl;
2494 QPointF tr;
2495 QPointF br;
2496 QPointF bl;
2497 if (!d->identityMatrix) {
2498 const QTransform &x = d->matrix;
2499 tl = x.map(rect.topLeft());
2500 tr = x.map(rect.topRight());
2501 br = x.map(rect.bottomRight());
2502 bl = x.map(rect.bottomLeft());
2503 } else {
2504 tl = rect.topLeft();
2505 tr = rect.topRight();
2506 br = rect.bottomRight();
2507 bl = rect.bottomLeft();
2508 }
2509 QPointF scrollOffset(d->horizontalScroll(), d->verticalScroll());
2510 tl -= scrollOffset;
2511 tr -= scrollOffset;
2512 br -= scrollOffset;
2513 bl -= scrollOffset;
2514
2515 QPolygon poly(4);
2516 poly[0] = tl.toPoint();
2517 poly[1] = tr.toPoint();
2518 poly[2] = br.toPoint();
2519 poly[3] = bl.toPoint();
2520 return poly;
2521}
2522
2523/*!
2524 \fn QGraphicsView::mapFromScene(qreal x, qreal y, qreal w, qreal h) const
2525
2526 This function is provided for convenience. It's equivalent to
2527 calling mapFromScene(QRectF(\a x, \a y, \a w, \a h)).
2528*/
2529
2530/*!
2531 Returns the scene coordinate polygon \a polygon to a viewport coordinate
2532 polygon.
2533
2534 \sa mapToScene()
2535*/
2536QPolygon QGraphicsView::mapFromScene(const QPolygonF &polygon) const
2537{
2538 QPolygon poly;
2539 poly.reserve(polygon.size());
2540 for (const QPointF &point : polygon)
2541 poly << mapFromScene(point);
2542 return poly;
2543}
2544
2545/*!
2546 Returns the scene coordinate painter path \a path to a viewport coordinate
2547 painter path.
2548
2549 \sa mapToScene()
2550*/
2551QPainterPath QGraphicsView::mapFromScene(const QPainterPath &path) const
2552{
2553 Q_D(const QGraphicsView);
2554 QTransform matrix = d->matrix;
2555 matrix *= QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
2556 return matrix.map(path);
2557}
2558
2559/*!
2560 \reimp
2561*/
2562QVariant QGraphicsView::inputMethodQuery(Qt::InputMethodQuery query) const
2563{
2564 Q_D(const QGraphicsView);
2565 if (!d->scene)
2566 return QVariant();
2567
2568 QVariant value = d->scene->inputMethodQuery(query);
2569 if (value.userType() == QMetaType::QRectF)
2570 value = d->mapRectFromScene(value.toRectF());
2571 else if (value.userType() == QMetaType::QPointF)
2572 value = mapFromScene(value.toPointF());
2573 else if (value.userType() == QMetaType::QRect)
2574 value = d->mapRectFromScene(value.toRect()).toRect();
2575 else if (value.userType() == QMetaType::QPoint)
2576 value = mapFromScene(value.toPoint());
2577 return value;
2578}
2579
2580/*!
2581 \property QGraphicsView::backgroundBrush
2582 \brief the background brush of the scene.
2583
2584 This property sets the background brush for the scene in this view. It is
2585 used to override the scene's own background, and defines the behavior of
2586 drawBackground(). To provide custom background drawing for this view, you
2587 can reimplement drawBackground() instead.
2588
2589 By default, this property contains a brush with the Qt::NoBrush pattern.
2590
2591 \sa QGraphicsScene::backgroundBrush, foregroundBrush
2592*/
2593QBrush QGraphicsView::backgroundBrush() const
2594{
2595 Q_D(const QGraphicsView);
2596 return d->backgroundBrush;
2597}
2598void QGraphicsView::setBackgroundBrush(const QBrush &brush)
2599{
2600 Q_D(QGraphicsView);
2601 d->backgroundBrush = brush;
2602 d->updateAll();
2603
2604 if (d->cacheMode & CacheBackground) {
2605 // Invalidate the background pixmap
2606 d->mustResizeBackgroundPixmap = true;
2607 }
2608}
2609
2610/*!
2611 \property QGraphicsView::foregroundBrush
2612 \brief the foreground brush of the scene.
2613
2614 This property sets the foreground brush for the scene in this view. It is
2615 used to override the scene's own foreground, and defines the behavior of
2616 drawForeground(). To provide custom foreground drawing for this view, you
2617 can reimplement drawForeground() instead.
2618
2619 By default, this property contains a brush with the Qt::NoBrush pattern.
2620
2621 \sa QGraphicsScene::foregroundBrush, backgroundBrush
2622*/
2623QBrush QGraphicsView::foregroundBrush() const
2624{
2625 Q_D(const QGraphicsView);
2626 return d->foregroundBrush;
2627}
2628void QGraphicsView::setForegroundBrush(const QBrush &brush)
2629{
2630 Q_D(QGraphicsView);
2631 d->foregroundBrush = brush;
2632 d->updateAll();
2633}
2634
2635/*!
2636 Schedules an update of the scene rectangles \a rects.
2637
2638 \sa QGraphicsScene::changed()
2639*/
2640void QGraphicsView::updateScene(const QList<QRectF> &rects)
2641{
2642 // ### Note: Since 4.5, this slot is only called if the user explicitly
2643 // establishes a connection between the scene and the view, as the scene
2644 // and view are no longer connected. We need to keep it working (basically
2645 // leave it as it is), but the new delivery path is through
2646 // QGraphicsScenePrivate::itemUpdate().
2647 Q_D(QGraphicsView);
2648 if (d->fullUpdatePending || d->viewportUpdateMode == QGraphicsView::NoViewportUpdate)
2649 return;
2650
2651 // Extract and reset dirty scene rect info.
2652 QList<QRect> dirtyViewportRects;
2653 dirtyViewportRects.reserve(d->dirtyRegion.rectCount() + rects.size());
2654 for (const QRect &dirtyRect : d->dirtyRegion)
2655 dirtyViewportRects += dirtyRect;
2656 d->dirtyRegion = QRegion();
2657 d->dirtyBoundingRect = QRect();
2658
2659 bool fullUpdate = !d->accelerateScrolling || d->viewportUpdateMode == QGraphicsView::FullViewportUpdate;
2660 bool boundingRectUpdate = (d->viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate)
2661 || (d->viewportUpdateMode == QGraphicsView::SmartViewportUpdate
2662 && ((dirtyViewportRects.size() + rects.size()) >= QGRAPHICSVIEW_REGION_RECT_THRESHOLD));
2663
2664 QRegion updateRegion;
2665 QRect boundingRect;
2666 QRect viewportRect = viewport()->rect();
2667 bool redraw = false;
2668 QTransform transform = viewportTransform();
2669
2670 // Convert scene rects to viewport rects.
2671 for (const QRectF &rect : rects) {
2672 QRect xrect = transform.mapRect(rect).toAlignedRect();
2673 if (!(d->optimizationFlags & DontAdjustForAntialiasing))
2674 xrect.adjust(-2, -2, 2, 2);
2675 else
2676 xrect.adjust(-1, -1, 1, 1);
2677 if (!viewportRect.intersects(xrect))
2678 continue;
2679 dirtyViewportRects << xrect;
2680 }
2681
2682 for (const QRect &rect : std::as_const(dirtyViewportRects)) {
2683 // Add the exposed rect to the update region. In rect update
2684 // mode, we only count the bounding rect of items.
2685 if (!boundingRectUpdate) {
2686 updateRegion += rect;
2687 } else {
2688 boundingRect |= rect;
2689 }
2690 redraw = true;
2691 if (fullUpdate) {
2692 // If fullUpdate is true and we found a visible dirty rect,
2693 // we're done.
2694 break;
2695 }
2696 }
2697
2698 if (!redraw)
2699 return;
2700
2701 if (fullUpdate)
2702 viewport()->update();
2703 else if (boundingRectUpdate)
2704 viewport()->update(boundingRect);
2705 else
2706 viewport()->update(updateRegion);
2707}
2708
2709/*!
2710 Notifies QGraphicsView that the scene's scene rect has changed. \a rect
2711 is the new scene rect. If the view already has an explicitly set scene
2712 rect, this function does nothing.
2713
2714 \sa sceneRect, QGraphicsScene::sceneRectChanged()
2715*/
2716void QGraphicsView::updateSceneRect(const QRectF &rect)
2717{
2718 Q_D(QGraphicsView);
2719 if (!d->hasSceneRect) {
2720 d->sceneRect = rect;
2721 d->recalculateContentSize();
2722 }
2723}
2724
2725/*!
2726 This slot is called by QAbstractScrollArea after setViewport() has been
2727 called. Reimplement this function in a subclass of QGraphicsView to
2728 initialize the new viewport \a widget before it is used.
2729
2730 \sa setViewport()
2731*/
2732void QGraphicsView::setupViewport(QWidget *widget)
2733{
2734 Q_D(QGraphicsView);
2735
2736 if (!widget) {
2737 qWarning("QGraphicsView::setupViewport: cannot initialize null widget");
2738 return;
2739 }
2740
2741 const bool isGLWidget = widget->inherits("QOpenGLWidget");
2742
2743 d->accelerateScrolling = !(isGLWidget);
2744
2745 widget->setFocusPolicy(Qt::StrongFocus);
2746
2747 if (isGLWidget)
2748 d->stereoEnabled = QWidgetPrivate::get(widget)->isStereoEnabled();
2749
2750 if (!isGLWidget) {
2751 // autoFillBackground enables scroll acceleration.
2752 widget->setAutoFillBackground(true);
2753 }
2754
2755 // We are only interested in mouse tracking if items
2756 // accept hover events or use non-default cursors or if
2757 // AnchorUnderMouse is used as transformation or resize anchor.
2758 if ((d->scene && (!d->scene->d_func()->allItemsIgnoreHoverEvents
2759 || !d->scene->d_func()->allItemsUseDefaultCursor))
2760 || d->transformationAnchor == AnchorUnderMouse
2761 || d->resizeAnchor == AnchorUnderMouse) {
2762 widget->setMouseTracking(true);
2763 }
2764
2765 // enable touch events if any items is interested in them
2766 if (d->scene && !d->scene->d_func()->allItemsIgnoreTouchEvents)
2767 widget->setAttribute(Qt::WA_AcceptTouchEvents);
2768
2769#ifndef QT_NO_GESTURES
2770 if (d->scene) {
2771 const auto gestures = d->scene->d_func()->grabbedGestures.keys();
2772 for (Qt::GestureType gesture : gestures)
2773 widget->grabGesture(gesture);
2774 }
2775#endif
2776
2777 widget->setAcceptDrops(acceptDrops());
2778}
2779
2780/*!
2781 \reimp
2782*/
2783bool QGraphicsView::event(QEvent *event)
2784{
2785 Q_D(QGraphicsView);
2786
2787 if (d->sceneInteractionAllowed) {
2788 switch (event->type()) {
2789 case QEvent::ShortcutOverride:
2790 if (d->scene)
2791 return QCoreApplication::sendEvent(d->scene, event);
2792 break;
2793 case QEvent::KeyPress:
2794 if (d->scene) {
2795 QKeyEvent *k = static_cast<QKeyEvent *>(event);
2796 if (k->key() == Qt::Key_Tab || k->key() == Qt::Key_Backtab) {
2797 // Send the key events to the scene. This will invoke the
2798 // scene's tab focus handling, and if the event is
2799 // accepted, we return (prevent further event delivery),
2800 // and the base implementation will call QGraphicsView's
2801 // focusNextPrevChild() function. If the event is ignored,
2802 // we fall back to standard tab focus handling.
2803 QCoreApplication::sendEvent(d->scene, event);
2804 if (event->isAccepted())
2805 return true;
2806 // Ensure the event doesn't propagate just because the
2807 // scene ignored it. If the event propagates, then tab
2808 // handling will be called twice (this and parent).
2809 event->accept();
2810 }
2811 }
2812 break;
2813 default:
2814 break;
2815 }
2816 }
2817
2818 return QAbstractScrollArea::event(event);
2819}
2820
2821/*!
2822 \reimp
2823*/
2824bool QGraphicsView::viewportEvent(QEvent *event)
2825{
2826 Q_D(QGraphicsView);
2827 if (!d->scene)
2828 return QAbstractScrollArea::viewportEvent(event);
2829
2830 switch (event->type()) {
2831 case QEvent::Enter:
2832 QCoreApplication::sendEvent(d->scene, event);
2833 break;
2834 case QEvent::WindowActivate:
2835 QCoreApplication::sendEvent(d->scene, event);
2836 break;
2837 case QEvent::WindowDeactivate:
2838 // ### This is a temporary fix for until we get proper mouse
2839 // grab events. mouseGrabberItem should be set to 0 if we lose
2840 // the mouse grab.
2841 // Remove all popups when the scene loses focus.
2842 if (!d->scene->d_func()->popupWidgets.isEmpty())
2843 d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.constFirst());
2844 QCoreApplication::sendEvent(d->scene, event);
2845 break;
2846 case QEvent::Show:
2847 if (d->scene && isActiveWindow()) {
2848 QEvent windowActivate(QEvent::WindowActivate);
2849 QCoreApplication::sendEvent(d->scene, &windowActivate);
2850 }
2851 break;
2852 case QEvent::Hide:
2853 // spontaneous event will generate a WindowDeactivate.
2854 if (!event->spontaneous() && d->scene && isActiveWindow()) {
2855 QEvent windowDeactivate(QEvent::WindowDeactivate);
2856 QCoreApplication::sendEvent(d->scene, &windowDeactivate);
2857 }
2858 break;
2859 case QEvent::Leave: {
2860 // ### This is a temporary fix for until we get proper mouse grab
2861 // events. activeMouseGrabberItem should be set to 0 if we lose the
2862 // mouse grab.
2863 if ((QApplication::activePopupWidget() && QApplication::activePopupWidget() != window())
2864 || (QApplication::activeModalWidget() && QApplication::activeModalWidget() != window())
2865 || (QApplication::activeWindow() != window())) {
2866 if (!d->scene->d_func()->popupWidgets.isEmpty())
2867 d->scene->d_func()->removePopup(d->scene->d_func()->popupWidgets.constFirst());
2868 }
2869 d->useLastMouseEvent = false;
2870 QGraphicsSceneEvent leaveEvent(QEvent::GraphicsSceneLeave);
2871 leaveEvent.setWidget(viewport());
2872 QCoreApplication::sendEvent(d->scene, &leaveEvent);
2873 event->setAccepted(leaveEvent.isAccepted());
2874 break;
2875 }
2876#if QT_CONFIG(tooltip)
2877 case QEvent::ToolTip: {
2878 QHelpEvent *toolTip = static_cast<QHelpEvent *>(event);
2879 QGraphicsSceneHelpEvent helpEvent(QEvent::GraphicsSceneHelp);
2880 helpEvent.setWidget(viewport());
2881 helpEvent.setScreenPos(toolTip->globalPos());
2882 helpEvent.setScenePos(mapToScene(toolTip->pos()));
2883 QCoreApplication::sendEvent(d->scene, &helpEvent);
2884 toolTip->setAccepted(helpEvent.isAccepted());
2885 return true;
2886 }
2887#endif
2888 case QEvent::Paint:
2889 // Reset full update
2890 d->fullUpdatePending = false;
2891 d->dirtyScrollOffset = QPoint();
2892 if (d->scene) {
2893 // Check if this view reimplements the updateScene slot; if it
2894 // does, we can't do direct update delivery and have to fall back
2895 // to connecting the changed signal.
2896 if (!d->updateSceneSlotReimplementedChecked) {
2897 d->updateSceneSlotReimplementedChecked = true;
2898 const QMetaObject *mo = metaObject();
2899 if (mo != &QGraphicsView::staticMetaObject) {
2900 if (mo->indexOfSlot("updateScene(QList<QRectF>)")
2901 != QGraphicsView::staticMetaObject.indexOfSlot("updateScene(QList<QRectF>)")) {
2902 connect(d->scene, SIGNAL(changed(QList<QRectF>)),
2903 this, SLOT(updateScene(QList<QRectF>)));
2904 }
2905 }
2906 }
2907 }
2908 break;
2909 case QEvent::TouchBegin:
2910 case QEvent::TouchUpdate:
2911 case QEvent::TouchEnd:
2912 {
2913 if (!isEnabled())
2914 return false;
2915
2916 if (d->scene && d->sceneInteractionAllowed) {
2917 // Convert and deliver the touch event to the scene.
2918 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
2919 QMutableTouchEvent::setTarget(touchEvent, viewport());
2920 QGraphicsViewPrivate::translateTouchEvent(d, touchEvent);
2921 QCoreApplication::sendEvent(d->scene, touchEvent);
2922 } else {
2923 event->ignore();
2924 }
2925
2926 return true;
2927 }
2928#ifndef QT_NO_GESTURES
2929 case QEvent::Gesture:
2930 case QEvent::GestureOverride:
2931 {
2932 if (!isEnabled())
2933 return false;
2934
2935 if (d->scene && d->sceneInteractionAllowed) {
2936 QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(event);
2937 gestureEvent->setWidget(viewport());
2938 QCoreApplication::sendEvent(d->scene, gestureEvent);
2939 }
2940 return true;
2941 }
2942#endif // QT_NO_GESTURES
2943 default:
2944 break;
2945 }
2946
2947 return QAbstractScrollArea::viewportEvent(event);
2948}
2949
2950#ifndef QT_NO_CONTEXTMENU
2951/*!
2952 \reimp
2953*/
2954void QGraphicsView::contextMenuEvent(QContextMenuEvent *event)
2955{
2956 Q_D(QGraphicsView);
2957 if (!d->scene || !d->sceneInteractionAllowed)
2958 return;
2959
2960 d->mousePressViewPoint = event->pos();
2961 d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
2962 d->mousePressScreenPoint = event->globalPos();
2963 d->lastMouseMoveScenePoint = d->mousePressScenePoint;
2964 d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
2965
2966 QGraphicsSceneContextMenuEvent contextEvent(QEvent::GraphicsSceneContextMenu);
2967 contextEvent.setWidget(viewport());
2968 contextEvent.setScenePos(d->mousePressScenePoint);
2969 contextEvent.setScreenPos(d->mousePressScreenPoint);
2970 contextEvent.setModifiers(event->modifiers());
2971 contextEvent.setReason((QGraphicsSceneContextMenuEvent::Reason)(event->reason()));
2972 contextEvent.setAccepted(event->isAccepted());
2973 contextEvent.setTimestamp(event->timestamp());
2974 QCoreApplication::sendEvent(d->scene, &contextEvent);
2975 event->setAccepted(contextEvent.isAccepted());
2976}
2977#endif // QT_NO_CONTEXTMENU
2978
2979#if QT_CONFIG(draganddrop)
2980/*!
2981 \reimp
2982*/
2983void QGraphicsView::dropEvent(QDropEvent *event)
2984{
2985 Q_D(QGraphicsView);
2986 if (!d->scene || !d->sceneInteractionAllowed)
2987 return;
2988
2989 // Generate a scene event.
2990 QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDrop);
2991 d->populateSceneDragDropEvent(&sceneEvent, event);
2992
2993 // Send it to the scene.
2994 QCoreApplication::sendEvent(d->scene, &sceneEvent);
2995
2996 // Accept the originating event if the scene accepted the scene event.
2997 event->setAccepted(sceneEvent.isAccepted());
2998 if (sceneEvent.isAccepted())
2999 event->setDropAction(sceneEvent.dropAction());
3000
3001 delete d->lastDragDropEvent;
3002 d->lastDragDropEvent = nullptr;
3003}
3004
3005/*!
3006 \reimp
3007*/
3008void QGraphicsView::dragEnterEvent(QDragEnterEvent *event)
3009{
3010 Q_D(QGraphicsView);
3011 if (!d->scene || !d->sceneInteractionAllowed)
3012 return;
3013
3014 // Disable replaying of mouse move events.
3015 d->useLastMouseEvent = false;
3016
3017 // Generate a scene event.
3018 QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragEnter);
3019 d->populateSceneDragDropEvent(&sceneEvent, event);
3020
3021 // Store it for later use.
3022 d->storeDragDropEvent(&sceneEvent);
3023
3024 // Send it to the scene.
3025 QCoreApplication::sendEvent(d->scene, &sceneEvent);
3026
3027 // Accept the originating event if the scene accepted the scene event.
3028 if (sceneEvent.isAccepted()) {
3029 event->setAccepted(true);
3030 event->setDropAction(sceneEvent.dropAction());
3031 }
3032}
3033
3034/*!
3035 \reimp
3036*/
3037void QGraphicsView::dragLeaveEvent(QDragLeaveEvent *event)
3038{
3039 Q_D(QGraphicsView);
3040 if (!d->scene || !d->sceneInteractionAllowed)
3041 return;
3042 if (!d->lastDragDropEvent) {
3043 qWarning("QGraphicsView::dragLeaveEvent: drag leave received before drag enter");
3044 return;
3045 }
3046
3047 // Generate a scene event.
3048 QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragLeave);
3049 sceneEvent.setScenePos(d->lastDragDropEvent->scenePos());
3050 sceneEvent.setScreenPos(d->lastDragDropEvent->screenPos());
3051 sceneEvent.setButtons(d->lastDragDropEvent->buttons());
3052 sceneEvent.setModifiers(d->lastDragDropEvent->modifiers());
3053 sceneEvent.setPossibleActions(d->lastDragDropEvent->possibleActions());
3054 sceneEvent.setProposedAction(d->lastDragDropEvent->proposedAction());
3055 sceneEvent.setDropAction(d->lastDragDropEvent->dropAction());
3056 sceneEvent.setMimeData(d->lastDragDropEvent->mimeData());
3057 sceneEvent.setWidget(d->lastDragDropEvent->widget());
3058 sceneEvent.setSource(d->lastDragDropEvent->source());
3059 delete d->lastDragDropEvent;
3060 d->lastDragDropEvent = nullptr;
3061
3062 // Send it to the scene.
3063 QCoreApplication::sendEvent(d->scene, &sceneEvent);
3064
3065 // Accept the originating event if the scene accepted the scene event.
3066 if (sceneEvent.isAccepted())
3067 event->setAccepted(true);
3068}
3069
3070/*!
3071 \reimp
3072*/
3073void QGraphicsView::dragMoveEvent(QDragMoveEvent *event)
3074{
3075 Q_D(QGraphicsView);
3076 if (!d->scene || !d->sceneInteractionAllowed)
3077 return;
3078
3079 // Generate a scene event.
3080 QGraphicsSceneDragDropEvent sceneEvent(QEvent::GraphicsSceneDragMove);
3081 d->populateSceneDragDropEvent(&sceneEvent, event);
3082
3083 // Store it for later use.
3084 d->storeDragDropEvent(&sceneEvent);
3085
3086 // Send it to the scene.
3087 QCoreApplication::sendEvent(d->scene, &sceneEvent);
3088
3089 // Ignore the originating event if the scene ignored the scene event.
3090 event->setAccepted(sceneEvent.isAccepted());
3091 if (sceneEvent.isAccepted())
3092 event->setDropAction(sceneEvent.dropAction());
3093}
3094#endif // QT_CONFIG(draganddrop)
3095
3096/*!
3097 \reimp
3098*/
3099void QGraphicsView::focusInEvent(QFocusEvent *event)
3100{
3101 Q_D(QGraphicsView);
3102 d->updateInputMethodSensitivity();
3103 QAbstractScrollArea::focusInEvent(event);
3104 if (d->scene)
3105 QCoreApplication::sendEvent(d->scene, event);
3106 // Pass focus on if the scene cannot accept focus.
3107 if (!d->scene || !event->isAccepted())
3108 QAbstractScrollArea::focusInEvent(event);
3109}
3110
3111/*!
3112 \reimp
3113*/
3114bool QGraphicsView::focusNextPrevChild(bool next)
3115{
3116 return QAbstractScrollArea::focusNextPrevChild(next);
3117}
3118
3119/*!
3120 \reimp
3121*/
3122void QGraphicsView::focusOutEvent(QFocusEvent *event)
3123{
3124 Q_D(QGraphicsView);
3125 QAbstractScrollArea::focusOutEvent(event);
3126 if (d->scene)
3127 QCoreApplication::sendEvent(d->scene, event);
3128}
3129
3130/*!
3131 \reimp
3132*/
3133void QGraphicsView::keyPressEvent(QKeyEvent *event)
3134{
3135 Q_D(QGraphicsView);
3136 if (!d->scene || !d->sceneInteractionAllowed) {
3137 QAbstractScrollArea::keyPressEvent(event);
3138 return;
3139 }
3140 QCoreApplication::sendEvent(d->scene, event);
3141 if (!event->isAccepted())
3142 QAbstractScrollArea::keyPressEvent(event);
3143}
3144
3145/*!
3146 \reimp
3147*/
3148void QGraphicsView::keyReleaseEvent(QKeyEvent *event)
3149{
3150 Q_D(QGraphicsView);
3151 if (!d->scene || !d->sceneInteractionAllowed)
3152 return;
3153 QCoreApplication::sendEvent(d->scene, event);
3154 if (!event->isAccepted())
3155 QAbstractScrollArea::keyReleaseEvent(event);
3156}
3157
3158/*!
3159 \reimp
3160*/
3161void QGraphicsView::mouseDoubleClickEvent(QMouseEvent *event)
3162{
3163 Q_D(QGraphicsView);
3164 if (!d->scene || !d->sceneInteractionAllowed)
3165 return;
3166
3167 d->storeMouseEvent(event);
3168 d->mousePressViewPoint = event->position().toPoint();
3169 d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
3170 d->mousePressScreenPoint = event->globalPosition().toPoint();
3171 d->lastMouseMoveScenePoint = d->mousePressScenePoint;
3172 d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
3173 d->mousePressButton = event->button();
3174
3175 QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);
3176 mouseEvent.setWidget(viewport());
3177 mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
3178 mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
3179 mouseEvent.setScenePos(mapToScene(d->mousePressViewPoint));
3180 mouseEvent.setScreenPos(d->mousePressScreenPoint);
3181 mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
3182 mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
3183 mouseEvent.setButtons(event->buttons());
3184 mouseEvent.setAccepted(false);
3185 mouseEvent.setButton(event->button());
3186 mouseEvent.setModifiers(event->modifiers());
3187 mouseEvent.setSource(event->source());
3188 mouseEvent.setFlags(event->flags());
3189 mouseEvent.setTimestamp(event->timestamp());
3190 if (event->spontaneous())
3191 qt_sendSpontaneousEvent(d->scene, &mouseEvent);
3192 else
3193 QCoreApplication::sendEvent(d->scene, &mouseEvent);
3194
3195 // Update the original mouse event accepted state.
3196 const bool isAccepted = mouseEvent.isAccepted();
3197 event->setAccepted(isAccepted);
3198
3199 // Update the last mouse event accepted state.
3200 d->lastMouseEvent->setAccepted(isAccepted);
3201}
3202
3203/*!
3204 \reimp
3205*/
3206void QGraphicsView::mousePressEvent(QMouseEvent *event)
3207{
3208 Q_D(QGraphicsView);
3209
3210 // Store this event for replaying, finding deltas, and for
3211 // scroll-dragging; even in non-interactive mode, scroll hand dragging is
3212 // allowed, so we store the event at the very top of this function.
3213 d->storeMouseEvent(event);
3214 d->lastMouseEvent->setAccepted(false);
3215
3216 if (d->sceneInteractionAllowed) {
3217 // Store some of the event's button-down data.
3218 d->mousePressViewPoint = event->position().toPoint();
3219 d->mousePressScenePoint = mapToScene(d->mousePressViewPoint);
3220 d->mousePressScreenPoint = event->globalPosition().toPoint();
3221 d->lastMouseMoveScenePoint = d->mousePressScenePoint;
3222 d->lastMouseMoveScreenPoint = d->mousePressScreenPoint;
3223 d->mousePressButton = event->button();
3224
3225 if (d->scene) {
3226 // Convert and deliver the mouse event to the scene.
3227 QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);
3228 mouseEvent.setWidget(viewport());
3229 mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
3230 mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
3231 mouseEvent.setScenePos(d->mousePressScenePoint);
3232 mouseEvent.setScreenPos(d->mousePressScreenPoint);
3233 mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
3234 mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
3235 mouseEvent.setButtons(event->buttons());
3236 mouseEvent.setButton(event->button());
3237 mouseEvent.setModifiers(event->modifiers());
3238 mouseEvent.setSource(event->source());
3239 mouseEvent.setFlags(event->flags());
3240 mouseEvent.setAccepted(false);
3241 mouseEvent.setTimestamp(event->timestamp());
3242 if (event->spontaneous())
3243 qt_sendSpontaneousEvent(d->scene, &mouseEvent);
3244 else
3245 QCoreApplication::sendEvent(d->scene, &mouseEvent);
3246
3247 // Update the original mouse event accepted state.
3248 bool isAccepted = mouseEvent.isAccepted();
3249 event->setAccepted(isAccepted);
3250
3251 // Update the last mouse event accepted state.
3252 d->lastMouseEvent->setAccepted(isAccepted);
3253
3254 if (isAccepted)
3255 return;
3256 }
3257 }
3258
3259#if QT_CONFIG(rubberband)
3260 if (d->dragMode == QGraphicsView::RubberBandDrag && !d->rubberBanding) {
3261 if (d->sceneInteractionAllowed) {
3262 // Rubberbanding is only allowed in interactive mode.
3263 event->accept();
3264 d->rubberBanding = true;
3265 d->rubberBandRect = QRect();
3266 if (d->scene) {
3267 bool extendSelection = (event->modifiers() & Qt::ControlModifier) != 0;
3268
3269 if (extendSelection) {
3270 d->rubberBandSelectionOperation = Qt::AddToSelection;
3271 } else {
3272 d->rubberBandSelectionOperation = Qt::ReplaceSelection;
3273 d->scene->clearSelection();
3274 }
3275 }
3276 }
3277 } else
3278#endif
3279 if (d->dragMode == QGraphicsView::ScrollHandDrag && event->button() == Qt::LeftButton) {
3280 // Left-button press in scroll hand mode initiates hand scrolling.
3281 event->accept();
3282 d->handScrolling = true;
3283 d->handScrollMotions = 0;
3284#ifndef QT_NO_CURSOR
3285 viewport()->setCursor(Qt::ClosedHandCursor);
3286#endif
3287 }
3288}
3289
3290/*!
3291 \reimp
3292*/
3293void QGraphicsView::mouseMoveEvent(QMouseEvent *event)
3294{
3295 Q_D(QGraphicsView);
3296
3297 if (d->dragMode == QGraphicsView::ScrollHandDrag) {
3298 if (d->handScrolling) {
3299 QScrollBar *hBar = horizontalScrollBar();
3300 QScrollBar *vBar = verticalScrollBar();
3301 QPoint delta = (event->position() - d->lastMouseEvent->position()).toPoint();
3302 hBar->setValue(hBar->value() + (isRightToLeft() ? delta.x() : -delta.x()));
3303 vBar->setValue(vBar->value() - delta.y());
3304
3305 // Detect how much we've scrolled to disambiguate scrolling from
3306 // clicking.
3307 ++d->handScrollMotions;
3308 }
3309 }
3310
3311 d->mouseMoveEventHandler(event);
3312}
3313
3314/*!
3315 \reimp
3316*/
3317void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
3318{
3319 Q_D(QGraphicsView);
3320
3321#if QT_CONFIG(rubberband)
3322 if (d->dragMode == QGraphicsView::RubberBandDrag && d->sceneInteractionAllowed && !event->buttons()) {
3323 d->clearRubberBand();
3324 } else
3325#endif
3326 if (d->dragMode == QGraphicsView::ScrollHandDrag && event->button() == Qt::LeftButton) {
3327#ifndef QT_NO_CURSOR
3328 // Restore the open hand cursor. ### There might be items
3329 // under the mouse that have a valid cursor at this time, so
3330 // we could repeat the steps from mouseMoveEvent().
3331 viewport()->setCursor(Qt::OpenHandCursor);
3332#endif
3333 d->handScrolling = false;
3334
3335 if (d->scene && d->sceneInteractionAllowed && !d->lastMouseEvent->isAccepted() && d->handScrollMotions <= 6) {
3336 // If we've detected very little motion during the hand drag, and
3337 // no item accepted the last event, we'll interpret that as a
3338 // click to the scene, and reset the selection.
3339 d->scene->clearSelection();
3340 }
3341 }
3342
3343 d->storeMouseEvent(event);
3344
3345 if (!d->sceneInteractionAllowed)
3346 return;
3347
3348 if (!d->scene)
3349 return;
3350
3351 QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);
3352 mouseEvent.setWidget(viewport());
3353 mouseEvent.setButtonDownScenePos(d->mousePressButton, d->mousePressScenePoint);
3354 mouseEvent.setButtonDownScreenPos(d->mousePressButton, d->mousePressScreenPoint);
3355 mouseEvent.setScenePos(mapToScene(event->position().toPoint()));
3356 mouseEvent.setScreenPos(event->globalPosition().toPoint());
3357 mouseEvent.setLastScenePos(d->lastMouseMoveScenePoint);
3358 mouseEvent.setLastScreenPos(d->lastMouseMoveScreenPoint);
3359 mouseEvent.setButtons(event->buttons());
3360 mouseEvent.setButton(event->button());
3361 mouseEvent.setModifiers(event->modifiers());
3362 mouseEvent.setSource(event->source());
3363 mouseEvent.setFlags(event->flags());
3364 mouseEvent.setAccepted(false);
3365 mouseEvent.setTimestamp(event->timestamp());
3366 if (event->spontaneous())
3367 qt_sendSpontaneousEvent(d->scene, &mouseEvent);
3368 else
3369 QCoreApplication::sendEvent(d->scene, &mouseEvent);
3370
3371 // Update the last and current mouse events' accepted state.
3372 d->lastMouseEvent->setAccepted(mouseEvent.isAccepted());
3373 event->setAccepted(mouseEvent.isAccepted());
3374
3375#ifndef QT_NO_CURSOR
3376 if (mouseEvent.isAccepted() && mouseEvent.buttons() == 0 && viewport()->testAttribute(Qt::WA_SetCursor)) {
3377 // The last mouse release on the viewport will trigger clearing the cursor.
3378 d->_q_unsetViewportCursor();
3379 }
3380#endif
3381}
3382
3383#if QT_CONFIG(wheelevent)
3384/*!
3385 \reimp
3386*/
3387void QGraphicsView::wheelEvent(QWheelEvent *event)
3388{
3389 Q_D(QGraphicsView);
3390 if (!d->scene || !d->sceneInteractionAllowed) {
3391 QAbstractScrollArea::wheelEvent(event);
3392 return;
3393 }
3394
3395 event->ignore();
3396
3397 QGraphicsSceneWheelEvent wheelEvent(QEvent::GraphicsSceneWheel);
3398 wheelEvent.setWidget(viewport());
3399 wheelEvent.setScenePos(mapToScene(event->position().toPoint()));
3400 wheelEvent.setScreenPos(event->globalPosition().toPoint());
3401 wheelEvent.setButtons(event->buttons());
3402 wheelEvent.setModifiers(event->modifiers());
3403 const bool horizontal = qAbs(event->angleDelta().x()) > qAbs(event->angleDelta().y());
3404 wheelEvent.setDelta(horizontal ? event->angleDelta().x() : event->angleDelta().y());
3405 wheelEvent.setPixelDelta(event->pixelDelta());
3406 wheelEvent.setPhase(event->phase());
3407 wheelEvent.setInverted(event->isInverted());
3408 wheelEvent.setOrientation(horizontal ? Qt::Horizontal : Qt::Vertical);
3409 wheelEvent.setAccepted(false);
3410 wheelEvent.setTimestamp(event->timestamp());
3411 QCoreApplication::sendEvent(d->scene, &wheelEvent);
3412 event->setAccepted(wheelEvent.isAccepted());
3413 if (!event->isAccepted())
3414 QAbstractScrollArea::wheelEvent(event);
3415}
3416#endif // QT_CONFIG(wheelevent)
3417
3418/*!
3419 \reimp
3420*/
3421void QGraphicsView::paintEvent(QPaintEvent *event)
3422{
3423 Q_D(QGraphicsView);
3424 if (!d->scene) {
3425 QAbstractScrollArea::paintEvent(event);
3426 return;
3427 }
3428
3429 // Set up painter state protection.
3430 d->scene->d_func()->painterStateProtection = !(d->optimizationFlags & DontSavePainterState);
3431
3432 // Determine the exposed region
3433 d->exposedRegion = event->region();
3434 QRectF exposedSceneRect = mapToScene(d->exposedRegion.boundingRect()).boundingRect();
3435
3436 // Set up the painter
3437 QPainter painter(viewport());
3438#if QT_CONFIG(rubberband)
3439 if (d->rubberBanding && !d->rubberBandRect.isEmpty())
3440 painter.save();
3441#endif
3442 // Set up render hints
3443 painter.setRenderHints(painter.renderHints(), false);
3444 painter.setRenderHints(d->renderHints, true);
3445
3446 // Set up viewport transform
3447 const bool viewTransformed = isTransformed();
3448 if (viewTransformed)
3449 painter.setWorldTransform(viewportTransform());
3450 const QTransform viewTransform = painter.worldTransform();
3451
3452 const auto actuallyDraw = [&]() {
3453 // Draw background
3454 if (d->cacheMode & CacheBackground) {
3455 // Recreate the background pixmap, and flag the whole background as
3456 // exposed.
3457 if (d->mustResizeBackgroundPixmap) {
3458 const qreal dpr = d->viewport->devicePixelRatio();
3459 d->backgroundPixmap = QPixmap(viewport()->size() * dpr);
3460 d->backgroundPixmap.setDevicePixelRatio(dpr);
3461 QBrush bgBrush = viewport()->palette().brush(viewport()->backgroundRole());
3462 if (!bgBrush.isOpaque())
3463 d->backgroundPixmap.fill(Qt::transparent);
3464 QPainter p(&d->backgroundPixmap);
3465 p.fillRect(0, 0, d->backgroundPixmap.width(), d->backgroundPixmap.height(), bgBrush);
3466 d->backgroundPixmapExposed = QRegion(viewport()->rect());
3467 d->mustResizeBackgroundPixmap = false;
3468 }
3469
3470 // Redraw exposed areas
3471 if (!d->backgroundPixmapExposed.isEmpty()) {
3472 QPainter backgroundPainter(&d->backgroundPixmap);
3473 backgroundPainter.setClipRegion(d->backgroundPixmapExposed, Qt::ReplaceClip);
3474 if (viewTransformed)
3475 backgroundPainter.setTransform(viewTransform);
3476 QRectF backgroundExposedSceneRect = mapToScene(d->backgroundPixmapExposed.boundingRect()).boundingRect();
3477 drawBackground(&backgroundPainter, backgroundExposedSceneRect);
3478 d->backgroundPixmapExposed = QRegion();
3479 }
3480
3481 // Blit the background from the background pixmap
3482 if (viewTransformed) {
3483 painter.setWorldTransform(QTransform());
3484 painter.drawPixmap(QPoint(), d->backgroundPixmap);
3485 painter.setWorldTransform(viewTransform);
3486 } else {
3487 painter.drawPixmap(QPoint(), d->backgroundPixmap);
3488 }
3489 } else {
3490 if (!(d->optimizationFlags & DontSavePainterState))
3491 painter.save();
3492
3493 drawBackground(&painter, exposedSceneRect);
3494 if (!(d->optimizationFlags & DontSavePainterState))
3495 painter.restore();
3496 }
3497
3498 // Items
3499 if (!(d->optimizationFlags & IndirectPainting)) {
3500 const quint32 oldRectAdjust = d->scene->d_func()->rectAdjust;
3501 if (d->optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)
3502 d->scene->d_func()->rectAdjust = 1;
3503 else
3504 d->scene->d_func()->rectAdjust = 2;
3505 d->scene->d_func()->drawItems(&painter, viewTransformed ? &viewTransform : nullptr,
3506 &d->exposedRegion, viewport());
3507 d->scene->d_func()->rectAdjust = oldRectAdjust;
3508 // Make sure the painter's world transform is restored correctly when
3509 // drawing without painter state protection (DontSavePainterState).
3510 // We only change the worldTransform() so there's no need to do a full-blown
3511 // save() and restore(). Also note that we don't have to do this in case of
3512 // IndirectPainting (the else branch), because in that case we always save()
3513 // and restore() in QGraphicsScene::drawItems().
3514 if (!d->scene->d_func()->painterStateProtection)
3515 painter.setOpacity(1.0);
3516 painter.setWorldTransform(viewTransform);
3517 } else {
3518 // Make sure we don't have unpolished items before we draw
3519 if (!d->scene->d_func()->unpolishedItems.isEmpty())
3520 d->scene->d_func()->_q_polishItems();
3521 // We reset updateAll here (after we've issued polish events)
3522 // so that we can discard update requests coming from polishEvent().
3523 d->scene->d_func()->updateAll = false;
3524
3525 // Find all exposed items
3526 bool allItems = false;
3527 QList<QGraphicsItem *> itemList = d->findItems(d->exposedRegion, &allItems, viewTransform);
3528 if (!itemList.isEmpty()) {
3529 // Generate the style options.
3530 const int numItems = itemList.size();
3531 QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid.
3532 QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems);
3533 QTransform transform(Qt::Uninitialized);
3534 for (int i = 0; i < numItems; ++i) {
3535 QGraphicsItem *item = itemArray[i];
3536 QGraphicsItemPrivate *itemd = item->d_ptr.data();
3537 itemd->initStyleOption(&styleOptionArray[i], viewTransform, d->exposedRegion, allItems);
3538 // Cache the item's area in view coordinates.
3539 // Note that we have to do this here in case the base class implementation
3540 // (QGraphicsScene::drawItems) is not called. If it is, we'll do this
3541 // operation twice, but that's the price one has to pay for using indirect
3542 // painting :-/.
3543 const QRectF brect = adjustedItemEffectiveBoundingRect(item);
3544 if (!itemd->itemIsUntransformable()) {
3545 transform = item->sceneTransform();
3546 if (viewTransformed)
3547 transform *= viewTransform;
3548 } else {
3549 transform = item->deviceTransform(viewTransform);
3550 }
3551 itemd->paintedViewBoundingRects.insert(d->viewport, transform.mapRect(brect).toRect());
3552 }
3553 // Draw the items.
3554 drawItems(&painter, numItems, itemArray, styleOptionArray);
3555 d->freeStyleOptionsArray(styleOptionArray);
3556 }
3557 }
3558
3559 // Foreground
3560 drawForeground(&painter, exposedSceneRect);
3561
3562 #if QT_CONFIG(rubberband)
3563 // Rubberband
3564 if (d->rubberBanding && !d->rubberBandRect.isEmpty()) {
3565 painter.restore();
3566 QStyleOptionRubberBand option;
3567 option.initFrom(viewport());
3568 option.rect = d->rubberBandRect;
3569 option.shape = QRubberBand::Rectangle;
3570
3571 QStyleHintReturnMask mask;
3572 if (viewport()->style()->styleHint(QStyle::SH_RubberBand_Mask, &option, viewport(), &mask)) {
3573 // painter clipping for masked rubberbands
3574 painter.setClipRegion(mask.region, Qt::IntersectClip);
3575 }
3576
3577 viewport()->style()->drawControl(QStyle::CE_RubberBand, &option, &painter, viewport());
3578 }
3579 #endif
3580 };
3581
3582 actuallyDraw();
3583
3584 // For stereo we want to draw everything twice, once to each buffer
3585 if (d->stereoEnabled) {
3586 QWidgetPrivate* w = QWidgetPrivate::get(viewport());
3587 if (w->toggleStereoTargetBuffer()) {
3588 actuallyDraw();
3589 w->toggleStereoTargetBuffer();
3590 }
3591 }
3592
3593 painter.end();
3594
3595 // Restore painter state protection.
3596 d->scene->d_func()->painterStateProtection = true;
3597}
3598
3599/*!
3600 \reimp
3601*/
3602void QGraphicsView::resizeEvent(QResizeEvent *event)
3603{
3604 Q_D(QGraphicsView);
3605 // Save the last center point - the resize may scroll the view, which
3606 // changes the center point.
3607 QPointF oldLastCenterPoint = d->lastCenterPoint;
3608
3609 QAbstractScrollArea::resizeEvent(event);
3610 d->recalculateContentSize();
3611
3612 // Restore the center point again.
3613 if (d->resizeAnchor == NoAnchor && !d->keepLastCenterPoint) {
3614 d->updateLastCenterPoint();
3615 } else {
3616 d->lastCenterPoint = oldLastCenterPoint;
3617 }
3618 d->centerView(d->resizeAnchor);
3619 d->keepLastCenterPoint = false;
3620
3621 if (d->cacheMode & CacheBackground) {
3622 // Invalidate the background pixmap
3623 d->mustResizeBackgroundPixmap = true;
3624 }
3625}
3626
3627/*!
3628 \reimp
3629*/
3630void QGraphicsView::scrollContentsBy(int dx, int dy)
3631{
3632 Q_D(QGraphicsView);
3633 d->dirtyScroll = true;
3634 if (d->transforming)
3635 return;
3636 if (isRightToLeft())
3637 dx = -dx;
3638
3639 if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate) {
3640 if (d->viewportUpdateMode != QGraphicsView::FullViewportUpdate) {
3641 if (d->accelerateScrolling) {
3642#if QT_CONFIG(rubberband)
3643 // Update new and old rubberband regions
3644 if (!d->rubberBandRect.isEmpty()) {
3645 QRegion rubberBandRegion(d->rubberBandRegion(viewport(), d->rubberBandRect));
3646 rubberBandRegion += rubberBandRegion.translated(-dx, -dy);
3647 viewport()->update(rubberBandRegion);
3648 }
3649#endif
3650 d->dirtyScrollOffset.rx() += dx;
3651 d->dirtyScrollOffset.ry() += dy;
3652 d->dirtyRegion.translate(dx, dy);
3653 viewport()->scroll(dx, dy);
3654 } else {
3655 d->updateAll();
3656 }
3657 } else {
3658 d->updateAll();
3659 }
3660 }
3661
3662 d->updateLastCenterPoint();
3663
3664 if (d->cacheMode & CacheBackground) {
3665 // Below, QPixmap::scroll() works in device pixels, while the delta values
3666 // and backgroundPixmapExposed are in device independent pixels.
3667 const qreal dpr = d->backgroundPixmap.devicePixelRatio();
3668 if (dpr == std::trunc(dpr)) {
3669 const qreal inverseDpr = qreal(1) / dpr;
3670
3671 // Scroll the background pixmap
3672 QRegion exposed;
3673 if (!d->backgroundPixmap.isNull())
3674 d->backgroundPixmap.scroll(dx * dpr, dy * dpr, d->backgroundPixmap.rect(), &exposed);
3675
3676 // Invalidate the background pixmap
3677 d->backgroundPixmapExposed.translate(dx, dy);
3678 const QRegion exposedScaled = QTransform::fromScale(inverseDpr, inverseDpr).map(exposed);
3679 d->backgroundPixmapExposed += exposedScaled;
3680 } else {
3681 // Fractional dpr: scroll+partial update can mismatch from rounding, so invalidate all
3682 d->backgroundPixmapExposed += QRegion(viewport()->rect());
3683 }
3684 }
3685
3686 // Always replay on scroll.
3687 if (d->sceneInteractionAllowed)
3688 d->replayLastMouseEvent();
3689}
3690
3691/*!
3692 \reimp
3693*/
3694void QGraphicsView::showEvent(QShowEvent *event)
3695{
3696 Q_D(QGraphicsView);
3697 d->recalculateContentSize();
3698 d->centerView(d->transformationAnchor);
3699 QAbstractScrollArea::showEvent(event);
3700}
3701
3702/*!
3703 \reimp
3704*/
3705void QGraphicsView::inputMethodEvent(QInputMethodEvent *event)
3706{
3707 Q_D(QGraphicsView);
3708 if (d->scene)
3709 QCoreApplication::sendEvent(d->scene, event);
3710}
3711
3712/*!
3713 Draws the background of the scene using \a painter, before any items and
3714 the foreground are drawn. Reimplement this function to provide a custom
3715 background for this view.
3716
3717 If all you want is to define a color, texture or gradient for the
3718 background, you can call setBackgroundBrush() instead.
3719
3720 All painting is done in \e scene coordinates. \a rect is the exposed
3721 rectangle.
3722
3723 The default implementation fills \a rect using the view's backgroundBrush.
3724 If no such brush is defined (the default), the scene's drawBackground()
3725 function is called instead.
3726
3727 \sa drawForeground(), QGraphicsScene::drawBackground()
3728*/
3729void QGraphicsView::drawBackground(QPainter *painter, const QRectF &rect)
3730{
3731 Q_D(QGraphicsView);
3732 if (d->scene && d->backgroundBrush.style() == Qt::NoBrush) {
3733 d->scene->drawBackground(painter, rect);
3734 return;
3735 }
3736
3737 const bool wasAa = painter->testRenderHint(QPainter::Antialiasing);
3738 if (wasAa)
3739 painter->setRenderHints(QPainter::Antialiasing, false);
3740 painter->fillRect(rect, d->backgroundBrush);
3741 if (wasAa)
3742 painter->setRenderHints(QPainter::Antialiasing, true);
3743}
3744
3745/*!
3746 Draws the foreground of the scene using \a painter, after the background
3747 and all items are drawn. Reimplement this function to provide a custom
3748 foreground for this view.
3749
3750 If all you want is to define a color, texture or gradient for the
3751 foreground, you can call setForegroundBrush() instead.
3752
3753 All painting is done in \e scene coordinates. \a rect is the exposed
3754 rectangle.
3755
3756 The default implementation fills \a rect using the view's foregroundBrush.
3757 If no such brush is defined (the default), the scene's drawForeground()
3758 function is called instead.
3759
3760 \sa drawBackground(), QGraphicsScene::drawForeground()
3761*/
3762void QGraphicsView::drawForeground(QPainter *painter, const QRectF &rect)
3763{
3764 Q_D(QGraphicsView);
3765 if (d->scene && d->foregroundBrush.style() == Qt::NoBrush) {
3766 d->scene->drawForeground(painter, rect);
3767 return;
3768 }
3769
3770 painter->fillRect(rect, d->foregroundBrush);
3771}
3772
3773/*!
3774 \deprecated
3775
3776 Draws the items \a items in the scene using \a painter, after the
3777 background and before the foreground are drawn. \a numItems is the number
3778 of items in \a items and options in \a options. \a options is a list of
3779 styleoptions; one for each item. Reimplement this function to provide
3780 custom item drawing for this view.
3781
3782 The default implementation calls the scene's drawItems() function.
3783
3784 Since Qt 4.6, this function is not called anymore unless
3785 the QGraphicsView::IndirectPainting flag is given as an Optimization
3786 flag.
3787
3788 \sa drawForeground(), drawBackground(), QGraphicsScene::drawItems()
3789*/
3790void QGraphicsView::drawItems(QPainter *painter, int numItems,
3791 QGraphicsItem *items[],
3792 const QStyleOptionGraphicsItem options[])
3793{
3794 Q_D(QGraphicsView);
3795 if (d->scene) {
3796 QWidget *widget = painter->device() == viewport() ? viewport() : nullptr;
3797 d->scene->drawItems(painter, numItems, items, options, widget);
3798 }
3799}
3800
3801/*!
3802 Returns the current transformation matrix for the view. If no current
3803 transformation is set, the identity matrix is returned.
3804
3805 \sa setTransform(), rotate(), scale(), shear(), translate()
3806*/
3807QTransform QGraphicsView::transform() const
3808{
3809 Q_D(const QGraphicsView);
3810 return d->matrix;
3811}
3812
3813/*!
3814 Returns a matrix that maps scene coordinates to viewport coordinates.
3815
3816 \sa mapToScene(), mapFromScene()
3817*/
3818QTransform QGraphicsView::viewportTransform() const
3819{
3820 Q_D(const QGraphicsView);
3821 QTransform moveMatrix = QTransform::fromTranslate(-d->horizontalScroll(), -d->verticalScroll());
3822 return d->identityMatrix ? moveMatrix : d->matrix * moveMatrix;
3823}
3824
3825/*!
3826 \since 4.6
3827
3828 Returns \c true if the view is transformed (i.e., a non-identity transform
3829 has been assigned, or the scrollbars are adjusted).
3830
3831 \sa setTransform(), horizontalScrollBar(), verticalScrollBar()
3832*/
3833bool QGraphicsView::isTransformed() const
3834{
3835 Q_D(const QGraphicsView);
3836 return !d->identityMatrix || d->horizontalScroll() || d->verticalScroll();
3837}
3838
3839/*!
3840 Sets the view's current transformation matrix to \a matrix.
3841
3842 If \a combine is true, then \a matrix is combined with the current matrix;
3843 otherwise, \a matrix \e replaces the current matrix. \a combine is false
3844 by default.
3845
3846 The transformation matrix transforms the scene into view coordinates. Using
3847 the default transformation, provided by the identity matrix, one pixel in
3848 the view represents one unit in the scene (e.g., a 10x10 rectangular item
3849 is drawn using 10x10 pixels in the view). If a 2x2 scaling matrix is
3850 applied, the scene will be drawn in 1:2 (e.g., a 10x10 rectangular item is
3851 then drawn using 20x20 pixels in the view).
3852
3853 Example:
3854
3855 \snippet code/src_gui_graphicsview_qgraphicsview.cpp 7
3856
3857 To simplify interaction with items using a transformed view, QGraphicsView
3858 provides mapTo... and mapFrom... functions that can translate between
3859 scene and view coordinates. For example, you can call mapToScene() to map
3860 a view coordinate to a floating point scene coordinate, or mapFromScene()
3861 to map from floating point scene coordinates to view coordinates.
3862
3863 \sa transform(), resetTransform(), rotate(), scale(), shear(), translate()
3864*/
3865void QGraphicsView::setTransform(const QTransform &matrix, bool combine )
3866{
3867 Q_D(QGraphicsView);
3868 QTransform oldMatrix = d->matrix;
3869 if (!combine)
3870 d->matrix = matrix;
3871 else
3872 d->matrix = matrix * d->matrix;
3873 if (oldMatrix == d->matrix)
3874 return;
3875
3876 d->identityMatrix = d->matrix.isIdentity();
3877 d->transforming = true;
3878 if (d->scene) {
3879 d->recalculateContentSize();
3880 d->centerView(d->transformationAnchor);
3881 } else {
3882 d->updateLastCenterPoint();
3883 }
3884
3885 if (d->sceneInteractionAllowed)
3886 d->replayLastMouseEvent();
3887 d->transforming = false;
3888
3889 // Any matrix operation requires a full update.
3890 d->updateAll();
3891}
3892
3893/*!
3894 Resets the view transformation to the identity matrix.
3895
3896 \sa transform(), setTransform()
3897*/
3898void QGraphicsView::resetTransform()
3899{
3900 setTransform(QTransform());
3901}
3902
3903QPointF QGraphicsViewPrivate::mapToScene(const QPointF &point) const
3904{
3905 QPointF p = point;
3906 p.rx() += horizontalScroll();
3907 p.ry() += verticalScroll();
3908 return identityMatrix ? p : matrix.inverted().map(p);
3909}
3910
3911QRectF QGraphicsViewPrivate::mapToScene(const QRectF &rect) const
3912{
3913 QPointF scrollOffset(horizontalScroll(), verticalScroll());
3914 QPointF tl = scrollOffset + rect.topLeft();
3915 QPointF tr = scrollOffset + rect.topRight();
3916 QPointF br = scrollOffset + rect.bottomRight();
3917 QPointF bl = scrollOffset + rect.bottomLeft();
3918
3919 QPolygonF poly(4);
3920 if (!identityMatrix) {
3921 QTransform x = matrix.inverted();
3922 poly[0] = x.map(tl);
3923 poly[1] = x.map(tr);
3924 poly[2] = x.map(br);
3925 poly[3] = x.map(bl);
3926 } else {
3927 poly[0] = tl;
3928 poly[1] = tr;
3929 poly[2] = br;
3930 poly[3] = bl;
3931 }
3932 return poly.boundingRect();
3933}
3934
3935QT_END_NAMESPACE
3936
3937#include "moc_qgraphicsview.cpp"
\inmodule QtGui
Combined button and popup list for selecting options.
bool qt_sendSpontaneousEvent(QObject *, QEvent *)
static bool intersectsViewport(const QRect &r, int width, int height)
static bool containsViewport(const QRect &r, int width, int height)
static const int QGRAPHICSVIEW_REGION_RECT_THRESHOLD
static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS
static void QRect_unite(QRect *rect, const QRect &other)
int q_round_bound(qreal d)