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
qabstractscrollarea.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#if QT_CONFIG(scrollarea)
8
9#include "qscrollbar.h"
10#include "qgesture.h"
11#include "qguiapplication.h"
12#include "qstyle.h"
13#include "qstyleoption.h"
14#include "qevent.h"
15#include "qdebug.h"
16#include "qboxlayout.h"
17#include "qpainter.h"
18#include "qmargins.h"
19#if QT_CONFIG(itemviews)
20#include "qheaderview.h"
21#endif
22
23#include "qabstractscrollarea_p.h"
24#include "qscrollbar_p.h"
25
26#include <private/qguiapplication_p.h>
27#include <qpa/qplatformtheme.h>
28
29#include <private/qapplication_p.h>
30
31QT_BEGIN_NAMESPACE
32
33using namespace Qt::StringLiterals;
34
35/*!
36 \class QAbstractScrollArea
37 \brief The QAbstractScrollArea widget provides a scrolling area with
38 on-demand scroll bars.
39
40 \ingroup abstractwidgets
41 \inmodule QtWidgets
42
43 QAbstractScrollArea is a low-level abstraction of a scrolling
44 area. The area provides a central widget called the viewport, in
45 which the contents of the area is to be scrolled (i.e, the
46 visible parts of the contents are rendered in the viewport).
47
48 Next to the viewport is a vertical scroll bar, and below is a
49 horizontal scroll bar. When all of the area contents fits in the
50 viewport, each scroll bar can be either visible or hidden
51 depending on the scroll bar's Qt::ScrollBarPolicy. When a scroll
52 bar is hidden, the viewport expands in order to cover all
53 available space. When a scroll bar becomes visible again, the
54 viewport shrinks in order to make room for the scroll bar.
55
56 It is possible to reserve a margin area around the viewport, see
57 setViewportMargins(). The feature is mostly used to place a
58 QHeaderView widget above or beside the scrolling area. Subclasses
59 of QAbstractScrollArea should implement margins.
60
61 When inheriting QAbstractScrollArea, you need to do the
62 following:
63
64 \list
65 \li Control the scroll bars by setting their
66 range, value, page step, and tracking their
67 movements.
68 \li Draw the contents of the area in the viewport according
69 to the values of the scroll bars.
70 \li Handle events received by the viewport in
71 viewportEvent() - notably resize events.
72 \li Use \c{viewport->update()} to update the contents of the
73 viewport instead of \l{QWidget::update()}{update()}
74 as all painting operations take place on the viewport.
75 \endlist
76
77 With a scroll bar policy of Qt::ScrollBarAsNeeded (the default),
78 QAbstractScrollArea shows scroll bars when they provide a non-zero
79 scrolling range, and hides them otherwise.
80
81 The scroll bars and viewport should be updated whenever the viewport
82 receives a resize event or the size of the contents changes.
83 The viewport also needs to be updated when the scroll bars
84 values change. The initial values of the scroll bars are often
85 set when the area receives new contents.
86
87 We give a simple example, in which we have implemented a scroll area
88 that can scroll any QWidget. We make the widget a child of the
89 viewport; this way, we do not have to calculate which part of
90 the widget to draw but can simply move the widget with
91 QWidget::move(). When the area contents or the viewport size
92 changes, we do the following:
93
94 \snippet myscrollarea/myscrollarea.cpp 1
95
96 When the scroll bars change value, we need to update the widget
97 position, i.e., find the part of the widget that is to be drawn in
98 the viewport:
99
100 \snippet myscrollarea/myscrollarea.cpp 0
101
102 In order to track scroll bar movements, reimplement the virtual
103 function scrollContentsBy(). In order to fine-tune scrolling
104 behavior, connect to a scroll bar's
105 QAbstractSlider::actionTriggered() signal and adjust the \l
106 QAbstractSlider::sliderPosition as you wish.
107
108 For convenience, QAbstractScrollArea makes all viewport events
109 available in the virtual viewportEvent() handler. QWidget's
110 specialized handlers are remapped to viewport events in the cases
111 where this makes sense. The remapped specialized handlers are:
112 paintEvent(), mousePressEvent(), mouseReleaseEvent(),
113 mouseDoubleClickEvent(), mouseMoveEvent(), wheelEvent(),
114 dragEnterEvent(), dragMoveEvent(), dragLeaveEvent(), dropEvent(),
115 contextMenuEvent(), and resizeEvent().
116
117 QScrollArea, which inherits QAbstractScrollArea, provides smooth
118 scrolling for any QWidget (i.e., the widget is scrolled pixel by
119 pixel). You only need to subclass QAbstractScrollArea if you need
120 more specialized behavior. This is, for instance, true if the
121 entire contents of the area is not suitable for being drawn on a
122 QWidget or if you do not want smooth scrolling.
123
124 \sa QScrollArea
125*/
126
127QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate()
128 :hbar(nullptr), vbar(nullptr), vbarpolicy(Qt::ScrollBarAsNeeded), hbarpolicy(Qt::ScrollBarAsNeeded),
129 shownOnce(false), inResize(false), sizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored),
130 viewport(nullptr), cornerWidget(nullptr), left(0), top(0), right(0), bottom(0),
131 xoffset(0), yoffset(0), viewportFilter(nullptr)
132{
133}
134
135QAbstractScrollAreaPrivate::~QAbstractScrollAreaPrivate()
136{
137}
138
139QAbstractScrollAreaScrollBarContainer::QAbstractScrollAreaScrollBarContainer(Qt::Orientation orientation, QWidget *parent)
140 :QWidget(parent), scrollBar(new QScrollBar(orientation, this)),
141 layout(new QBoxLayout(orientation == Qt::Horizontal ? QBoxLayout::LeftToRight : QBoxLayout::TopToBottom)),
142 orientation(orientation)
143{
144 setLayout(layout);
145 layout->setContentsMargins(QMargins());
146 layout->setSpacing(0);
147 layout->addWidget(scrollBar);
148 layout->setSizeConstraint(QLayout::SetMaximumSize);
149}
150
151/*! \internal
152 Adds a widget to the scroll bar container.
153*/
154void QAbstractScrollAreaScrollBarContainer::addWidget(QWidget *widget, LogicalPosition position)
155{
156 QSizePolicy policy = widget->sizePolicy();
157 if (orientation == Qt::Vertical)
158 policy.setHorizontalPolicy(QSizePolicy::Ignored);
159 else
160 policy.setVerticalPolicy(QSizePolicy::Ignored);
161 widget->setSizePolicy(policy);
162 widget->setParent(this);
163
164 const int insertIndex = (position & LogicalLeft) ? 0 : scrollBarLayoutIndex() + 1;
165 layout->insertWidget(insertIndex, widget);
166}
167
168/*! \internal
169 Returns a list of scroll-bar widgets for the given position. The scroll bar
170 itself is not returned.
171*/
172QWidgetList QAbstractScrollAreaScrollBarContainer::widgets(LogicalPosition position)
173{
174 QWidgetList list;
175 const int scrollBarIndex = scrollBarLayoutIndex();
176 if (position == LogicalLeft) {
177 list.reserve(scrollBarIndex);
178 for (int i = 0; i < scrollBarIndex; ++i)
179 list.append(layout->itemAt(i)->widget());
180 } else if (position == LogicalRight) {
181 const int layoutItemCount = layout->count();
182 list.reserve(layoutItemCount - (scrollBarIndex + 1));
183 for (int i = scrollBarIndex + 1; i < layoutItemCount; ++i)
184 list.append(layout->itemAt(i)->widget());
185 }
186 return list;
187}
188
189/*! \internal
190 Returns the layout index for the scroll bar. This needs to be
191 recalculated by a linear search for each use, since items in
192 the layout can be removed at any time (i.e. when a widget is
193 deleted or re-parented).
194*/
195int QAbstractScrollAreaScrollBarContainer::scrollBarLayoutIndex() const
196{
197 const int layoutItemCount = layout->count();
198 for (int i = 0; i < layoutItemCount; ++i) {
199 if (qobject_cast<QScrollBar *>(layout->itemAt(i)->widget()))
200 return i;
201 }
202 return -1;
203}
204
205/*! \internal
206*/
207void QAbstractScrollAreaPrivate::replaceScrollBar(QScrollBar *scrollBar,
208 Qt::Orientation orientation)
209{
210 Q_Q(QAbstractScrollArea);
211
212 QAbstractScrollAreaScrollBarContainer *container = scrollBarContainers[orientation];
213 bool horizontal = (orientation == Qt::Horizontal);
214 QScrollBar *oldBar = horizontal ? hbar : vbar;
215 if (horizontal)
216 hbar = scrollBar;
217 else
218 vbar = scrollBar;
219 scrollBar->setParent(container);
220 container->scrollBar = scrollBar;
221 container->layout->removeWidget(oldBar);
222 container->layout->insertWidget(0, scrollBar);
223 scrollBar->setVisible(oldBar->isVisibleTo(container));
224 scrollBar->setInvertedAppearance(oldBar->invertedAppearance());
225 scrollBar->setInvertedControls(oldBar->invertedControls());
226 scrollBar->setRange(oldBar->minimum(), oldBar->maximum());
227 scrollBar->setOrientation(oldBar->orientation());
228 scrollBar->setPageStep(oldBar->pageStep());
229 scrollBar->setSingleStep(oldBar->singleStep());
230 scrollBar->d_func()->viewMayChangeSingleStep = oldBar->d_func()->viewMayChangeSingleStep;
231 scrollBar->setSliderDown(oldBar->isSliderDown());
232 scrollBar->setSliderPosition(oldBar->sliderPosition());
233 scrollBar->setTracking(oldBar->hasTracking());
234 scrollBar->setValue(oldBar->value());
235 scrollBar->installEventFilter(q);
236 oldBar->removeEventFilter(q);
237 delete oldBar;
238
239 QObject::connect(scrollBar, SIGNAL(valueChanged(int)),
240 q, horizontal ? SLOT(_q_hslide(int)) : SLOT(_q_vslide(int)));
241 QObject::connect(scrollBar, SIGNAL(rangeChanged(int,int)),
242 q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
243}
244
245void QAbstractScrollAreaPrivate::init()
246{
247 Q_Q(QAbstractScrollArea);
248 viewport = new QWidget(q);
249 viewport->setObjectName("qt_scrollarea_viewport"_L1);
250 viewport->setBackgroundRole(QPalette::Base);
251 viewport->setAutoFillBackground(true);
252 scrollBarContainers[Qt::Horizontal] = new QAbstractScrollAreaScrollBarContainer(Qt::Horizontal, q);
253 scrollBarContainers[Qt::Horizontal]->setObjectName("qt_scrollarea_hcontainer"_L1);
254 hbar = scrollBarContainers[Qt::Horizontal]->scrollBar;
255 hbar->setRange(0,0);
256 scrollBarContainers[Qt::Horizontal]->setVisible(false);
257 hbar->installEventFilter(q);
258 QObject::connect(hbar, SIGNAL(valueChanged(int)), q, SLOT(_q_hslide(int)));
259 QObject::connect(hbar, SIGNAL(rangeChanged(int,int)), q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
260 scrollBarContainers[Qt::Vertical] = new QAbstractScrollAreaScrollBarContainer(Qt::Vertical, q);
261 scrollBarContainers[Qt::Vertical]->setObjectName("qt_scrollarea_vcontainer"_L1);
262 vbar = scrollBarContainers[Qt::Vertical]->scrollBar;
263 vbar->setRange(0,0);
264 scrollBarContainers[Qt::Vertical]->setVisible(false);
265 vbar->installEventFilter(q);
266 QObject::connect(vbar, SIGNAL(valueChanged(int)), q, SLOT(_q_vslide(int)));
267 QObject::connect(vbar, SIGNAL(rangeChanged(int,int)), q, SLOT(_q_showOrHideScrollBars()), Qt::QueuedConnection);
268 viewportFilter.reset(new QAbstractScrollAreaFilter(this));
269 viewport->installEventFilter(viewportFilter.data());
270 viewport->setFocusProxy(q);
271 q->setFocusPolicy(Qt::StrongFocus);
272 q->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
273 q->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
274 layoutChildren();
275#ifndef Q_OS_MACOS
276# ifndef QT_NO_GESTURES
277 viewport->grabGesture(Qt::PanGesture);
278# endif
279#endif
280}
281
282void QAbstractScrollAreaPrivate::layoutChildren()
283{
284 bool needH = false;
285 bool needV = false;
286 layoutChildren_helper(&needH, &needV);
287 // Call a second time if one scrollbar was needed and not the other to
288 // check if it needs to readjust accordingly
289 if (needH != needV)
290 layoutChildren_helper(&needH, &needV);
291}
292
293void QAbstractScrollAreaPrivate::layoutChildren_helper(bool *needHorizontalScrollbar, bool *needVerticalScrollbar)
294{
295 Q_Q(QAbstractScrollArea);
296 QStyleOptionSlider barOpt;
297
298 hbar->initStyleOption(&barOpt);
299 bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, hbar);
300 bool needh = *needHorizontalScrollbar || ((hbarpolicy != Qt::ScrollBarAlwaysOff) && ((hbarpolicy == Qt::ScrollBarAlwaysOn && !htransient)
301 || ((hbarpolicy == Qt::ScrollBarAsNeeded || htransient)
302 && hbar->minimum() < hbar->maximum() && !hbar->sizeHint().isEmpty())));
303 const int hscrollOverlap = hbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, hbar);
304
305 vbar->initStyleOption(&barOpt);
306 bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &barOpt, vbar);
307 bool needv = *needVerticalScrollbar || ((vbarpolicy != Qt::ScrollBarAlwaysOff) && ((vbarpolicy == Qt::ScrollBarAlwaysOn && !vtransient)
308 || ((vbarpolicy == Qt::ScrollBarAsNeeded || vtransient)
309 && vbar->minimum() < vbar->maximum() && !vbar->sizeHint().isEmpty())));
310 const int vscrollOverlap = vbar->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarOverlap, &barOpt, vbar);
311
312 QStyleOption opt(0);
313 opt.initFrom(q);
314
315 const int hsbExt = hbar->sizeHint().height();
316 const int vsbExt = vbar->sizeHint().width();
317 const QPoint extPoint(vsbExt, hsbExt);
318 const QSize extSize(vsbExt, hsbExt);
319
320 const QRect widgetRect = q->rect();
321
322 const bool hasCornerWidget = (cornerWidget != nullptr);
323
324 QPoint cornerOffset((needv && vscrollOverlap == 0) ? vsbExt : 0, (needh && hscrollOverlap == 0) ? hsbExt : 0);
325 QRect controlsRect;
326 QRect viewportRect;
327
328 // In FrameOnlyAroundContents mode the frame is drawn between the controls and
329 // the viewport, else the frame rect is equal to the widget rect.
330 if ((frameStyle != QFrame::NoFrame) &&
331 q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, q)) {
332 controlsRect = widgetRect;
333 const int spacing = q->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, q);
334 const QPoint cornerExtra(needv ? spacing + vscrollOverlap : 0, needh ? spacing + hscrollOverlap : 0);
335 QRect frameRect = widgetRect;
336 frameRect.adjust(0, 0, -cornerOffset.x() - cornerExtra.x(), -cornerOffset.y() - cornerExtra.y());
337 q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, frameRect));
338 // The frame rect needs to be in logical coords, however we need to flip
339 // the contentsRect back before passing it on to the viewportRect
340 // since the viewportRect has its logical coords calculated later.
341 viewportRect = QStyle::visualRect(opt.direction, opt.rect, q->contentsRect());
342 } else {
343 q->setFrameRect(QStyle::visualRect(opt.direction, opt.rect, widgetRect));
344 controlsRect = q->contentsRect();
345 viewportRect = QRect(controlsRect.topLeft(), controlsRect.bottomRight() - cornerOffset);
346 }
347
348 cornerOffset = QPoint(needv ? vsbExt : 0, needh ? hsbExt : 0);
349
350 // If we have a corner widget and are only showing one scroll bar, we need to move it
351 // to make room for the corner widget.
352 if (hasCornerWidget && ((needv && vscrollOverlap == 0) || (needh && hscrollOverlap == 0)))
353 cornerOffset = extPoint;
354
355 // The corner point is where the scroll bar rects, the corner widget rect and the
356 // viewport rect meets.
357 const QPoint cornerPoint(controlsRect.bottomRight() + QPoint(1, 1) - cornerOffset);
358
359 // Some styles paints the corner if both scorllbars are showing and there is
360 // no corner widget.
361 if (needv && needh && !hasCornerWidget && hscrollOverlap == 0 && vscrollOverlap == 0)
362 cornerPaintingRect = QStyle::visualRect(opt.direction, opt.rect, QRect(cornerPoint, extSize));
363 else
364 cornerPaintingRect = QRect();
365
366 // move the scrollbars away from top/left headers
367 int vHeaderRight = 0;
368 int hHeaderBottom = 0;
369#if QT_CONFIG(itemviews)
370 if ((vscrollOverlap > 0 && needv) || (hscrollOverlap > 0 && needh)) {
371 const QList<QHeaderView *> headers = q->findChildren<QHeaderView*>();
372 if (headers.size() <= 2) {
373 for (const QHeaderView *header : headers) {
374 const QRect geo = header->geometry();
375 if (header->orientation() == Qt::Vertical && header->isVisible() && QStyle::visualRect(opt.direction, opt.rect, geo).left() <= opt.rect.width() / 2)
376 vHeaderRight = QStyle::visualRect(opt.direction, opt.rect, geo).right();
377 else if (header->orientation() == Qt::Horizontal && header->isVisible() && geo.top() <= q->frameWidth())
378 hHeaderBottom = geo.bottom();
379 }
380 }
381 }
382#endif // QT_CONFIG(itemviews)
383 if (needh) {
384 QRect horizontalScrollBarRect(QPoint(controlsRect.left() + vHeaderRight, cornerPoint.y()), QPoint(cornerPoint.x() - 1, controlsRect.bottom()));
385
386 if (!hasCornerWidget && htransient)
387 horizontalScrollBarRect.adjust(0, 0, cornerOffset.x(), 0);
388 scrollBarContainers[Qt::Horizontal]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, horizontalScrollBarRect));
389 scrollBarContainers[Qt::Horizontal]->raise();
390 }
391
392 if (needv) {
393 QRect verticalScrollBarRect (QPoint(cornerPoint.x(), controlsRect.top() + hHeaderBottom), QPoint(controlsRect.right(), cornerPoint.y() - 1));
394 if (!hasCornerWidget && vtransient)
395 verticalScrollBarRect.adjust(0, 0, 0, cornerOffset.y());
396 scrollBarContainers[Qt::Vertical]->setGeometry(QStyle::visualRect(opt.direction, opt.rect, verticalScrollBarRect));
397 scrollBarContainers[Qt::Vertical]->raise();
398 }
399
400 if (cornerWidget) {
401 const QRect cornerWidgetRect(cornerPoint, controlsRect.bottomRight());
402 cornerWidget->setGeometry(QStyle::visualRect(opt.direction, opt.rect, cornerWidgetRect));
403 }
404
405 scrollBarContainers[Qt::Horizontal]->setVisible(needh);
406 scrollBarContainers[Qt::Vertical]->setVisible(needv);
407
408 if (q->isRightToLeft())
409 viewportRect.adjust(right, top, -left, -bottom);
410 else
411 viewportRect.adjust(left, top, -right, -bottom);
412 viewportRect = QStyle::visualRect(opt.direction, opt.rect, viewportRect);
413 viewportRect.translate(-overshoot);
414 viewport->setGeometry(viewportRect); // resize the viewport last
415
416 *needHorizontalScrollbar = needh;
417 *needVerticalScrollbar = needv;
418}
419
420/*!
421 \enum QAbstractScrollArea::SizeAdjustPolicy
422 \since 5.2
423
424 This enum specifies how the size hint of the QAbstractScrollArea should
425 adjust when the size of the viewport changes.
426
427 \value AdjustIgnored The scroll area will behave like before - and not do any adjust.
428 \value AdjustToContents The scroll area will always adjust to the viewport
429 \value AdjustToContentsOnFirstShow The scroll area will adjust to its viewport the first time it is shown.
430*/
431
432
433/*!
434 \internal
435
436 Creates a new QAbstractScrollAreaPrivate, \a dd with the given \a parent.
437*/
438QAbstractScrollArea::QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent)
439 :QFrame(dd, parent)
440{
441 Q_D(QAbstractScrollArea);
442 QT_TRY {
443 d->init();
444 } QT_CATCH(...) {
445 d->viewportFilter.reset();
446 QT_RETHROW;
447 }
448}
449
450/*!
451 Constructs a viewport.
452
453 The \a parent argument is sent to the QWidget constructor.
454*/
455QAbstractScrollArea::QAbstractScrollArea(QWidget *parent)
456 :QFrame(*new QAbstractScrollAreaPrivate, parent)
457{
458 Q_D(QAbstractScrollArea);
459 QT_TRY {
460 d->init();
461 } QT_CATCH(...) {
462 d->viewportFilter.reset();
463 QT_RETHROW;
464 }
465}
466
467
468/*!
469 Destroys the viewport.
470 */
471QAbstractScrollArea::~QAbstractScrollArea()
472{
473 Q_D(QAbstractScrollArea);
474 // reset it here, otherwise we'll have a dangling pointer in ~QWidget
475 d->viewportFilter.reset();
476}
477
478
479/*!
480 \since 4.2
481 Sets the viewport to be the given \a widget.
482 The QAbstractScrollArea will take ownership of the given \a widget.
483
484 If \a widget is \nullptr, QAbstractScrollArea will assign a new QWidget
485 instance for the viewport.
486
487 \sa viewport()
488*/
489void QAbstractScrollArea::setViewport(QWidget *widget)
490{
491 Q_D(QAbstractScrollArea);
492 if (widget != d->viewport) {
493 QWidget *oldViewport = d->viewport;
494 if (!widget)
495 widget = new QWidget;
496 d->viewport = widget;
497 d->viewport->setParent(this);
498 d->viewport->setFocusProxy(this);
499 d->viewport->installEventFilter(d->viewportFilter.data());
500#ifndef QT_NO_GESTURES
501 d->viewport->grabGesture(Qt::PanGesture);
502#endif
503 d->layoutChildren();
504#ifndef QT_NO_OPENGL
505 QWidgetPrivate::get(d->viewport)->initializeViewportFramebuffer();
506#endif
507 if (isVisible())
508 d->viewport->show();
509 setupViewport(widget);
510 delete oldViewport;
511 }
512}
513
514/*!
515 Returns the viewport widget.
516
517 Use the QScrollArea::widget() function to retrieve the contents of
518 the viewport widget.
519
520 \sa QScrollArea::widget()
521*/
522QWidget *QAbstractScrollArea::viewport() const
523{
524 Q_D(const QAbstractScrollArea);
525 return d->viewport;
526}
527
528
529/*!
530Returns the size of the viewport as if the scroll bars had no valid
531scrolling range.
532*/
533QSize QAbstractScrollArea::maximumViewportSize() const
534{
535 Q_D(const QAbstractScrollArea);
536 int f = 2 * d->frameWidth;
537 QSize max = size() - QSize(f + d->left + d->right, f + d->top + d->bottom);
538 // Count the sizeHint of the bar only if it is displayed.
539 if (d->vbarpolicy == Qt::ScrollBarAlwaysOn)
540 max.rwidth() -= d->vbar->sizeHint().width();
541 if (d->hbarpolicy == Qt::ScrollBarAlwaysOn)
542 max.rheight() -= d->hbar->sizeHint().height();
543 return max;
544}
545
546/*!
547 \property QAbstractScrollArea::verticalScrollBarPolicy
548 \brief the policy for the vertical scroll bar
549
550 The default policy is Qt::ScrollBarAsNeeded.
551
552 \sa horizontalScrollBarPolicy
553*/
554
555Qt::ScrollBarPolicy QAbstractScrollArea::verticalScrollBarPolicy() const
556{
557 Q_D(const QAbstractScrollArea);
558 return d->vbarpolicy;
559}
560
561void QAbstractScrollArea::setVerticalScrollBarPolicy(Qt::ScrollBarPolicy policy)
562{
563 Q_D(QAbstractScrollArea);
564 const Qt::ScrollBarPolicy oldPolicy = d->vbarpolicy;
565 d->vbarpolicy = policy;
566 if (isVisible())
567 d->layoutChildren();
568 if (oldPolicy != d->vbarpolicy)
569 d->scrollBarPolicyChanged(Qt::Vertical, d->vbarpolicy);
570}
571
572
573/*!
574 Returns the vertical scroll bar.
575
576 \sa verticalScrollBarPolicy, horizontalScrollBar()
577 */
578QScrollBar *QAbstractScrollArea::verticalScrollBar() const
579{
580 Q_D(const QAbstractScrollArea);
581 return d->vbar;
582}
583
584/*!
585 \since 4.2
586 Replaces the existing vertical scroll bar with \a scrollBar, and sets all
587 the former scroll bar's slider properties on the new scroll bar. The former
588 scroll bar is then deleted.
589
590 QAbstractScrollArea already provides vertical and horizontal scroll bars by
591 default. You can call this function to replace the default vertical
592 scroll bar with your own custom scroll bar.
593
594 \sa verticalScrollBar(), setHorizontalScrollBar()
595*/
596void QAbstractScrollArea::setVerticalScrollBar(QScrollBar *scrollBar)
597{
598 Q_D(QAbstractScrollArea);
599 if (Q_UNLIKELY(!scrollBar)) {
600 qWarning("QAbstractScrollArea::setVerticalScrollBar: Cannot set a null scroll bar");
601 return;
602 }
603
604 d->replaceScrollBar(scrollBar, Qt::Vertical);
605}
606
607/*!
608 \property QAbstractScrollArea::horizontalScrollBarPolicy
609 \brief the policy for the horizontal scroll bar
610
611 The default policy is Qt::ScrollBarAsNeeded.
612
613 \sa verticalScrollBarPolicy
614*/
615
616Qt::ScrollBarPolicy QAbstractScrollArea::horizontalScrollBarPolicy() const
617{
618 Q_D(const QAbstractScrollArea);
619 return d->hbarpolicy;
620}
621
622void QAbstractScrollArea::setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy policy)
623{
624 Q_D(QAbstractScrollArea);
625 const Qt::ScrollBarPolicy oldPolicy = d->hbarpolicy;
626 d->hbarpolicy = policy;
627 if (isVisible())
628 d->layoutChildren();
629 if (oldPolicy != d->hbarpolicy)
630 d->scrollBarPolicyChanged(Qt::Horizontal, d->hbarpolicy);
631}
632
633/*!
634 Returns the horizontal scroll bar.
635
636 \sa horizontalScrollBarPolicy, verticalScrollBar()
637 */
638QScrollBar *QAbstractScrollArea::horizontalScrollBar() const
639{
640 Q_D(const QAbstractScrollArea);
641 return d->hbar;
642}
643
644/*!
645 \since 4.2
646
647 Replaces the existing horizontal scroll bar with \a scrollBar, and sets all
648 the former scroll bar's slider properties on the new scroll bar. The former
649 scroll bar is then deleted.
650
651 QAbstractScrollArea already provides horizontal and vertical scroll bars by
652 default. You can call this function to replace the default horizontal
653 scroll bar with your own custom scroll bar.
654
655 \sa horizontalScrollBar(), setVerticalScrollBar()
656*/
657void QAbstractScrollArea::setHorizontalScrollBar(QScrollBar *scrollBar)
658{
659 Q_D(QAbstractScrollArea);
660 if (Q_UNLIKELY(!scrollBar)) {
661 qWarning("QAbstractScrollArea::setHorizontalScrollBar: Cannot set a null scroll bar");
662 return;
663 }
664
665 d->replaceScrollBar(scrollBar, Qt::Horizontal);
666}
667
668/*!
669 \since 4.2
670
671 Returns the widget in the corner between the two scroll bars.
672
673 By default, no corner widget is present.
674*/
675QWidget *QAbstractScrollArea::cornerWidget() const
676{
677 Q_D(const QAbstractScrollArea);
678 return d->cornerWidget;
679}
680
681/*!
682 \since 4.2
683
684 Sets the widget in the corner between the two scroll bars to be
685 \a widget.
686
687 You will probably also want to set at least one of the scroll bar
688 modes to \c AlwaysOn.
689
690 Passing \nullptr shows no widget in the corner.
691
692 Any previous corner widget is hidden.
693
694 You may call setCornerWidget() with the same widget at different
695 times.
696
697 All widgets set here will be deleted by the scroll area when it is
698 destroyed unless you separately reparent the widget after setting
699 some other corner widget (or \nullptr).
700
701 Any \e newly set widget should have no current parent.
702
703 By default, no corner widget is present.
704
705 \sa horizontalScrollBarPolicy, horizontalScrollBarPolicy
706*/
707void QAbstractScrollArea::setCornerWidget(QWidget *widget)
708{
709 Q_D(QAbstractScrollArea);
710 QWidget* oldWidget = d->cornerWidget;
711 if (oldWidget != widget) {
712 if (oldWidget)
713 oldWidget->hide();
714 d->cornerWidget = widget;
715
716 if (widget && widget->parentWidget() != this)
717 widget->setParent(this);
718
719 d->layoutChildren();
720 if (widget)
721 widget->show();
722 } else {
723 d->cornerWidget = widget;
724 d->layoutChildren();
725 }
726}
727
728/*!
729 \since 4.2
730 Adds \a widget as a scroll bar widget in the location specified
731 by \a alignment.
732
733 Scroll bar widgets are shown next to the horizontal or vertical
734 scroll bar, and can be placed on either side of it. If you want
735 the scroll bar widgets to be always visible, set the
736 scrollBarPolicy for the corresponding scroll bar to \c AlwaysOn.
737
738 \a alignment must be one of Qt::Alignleft and Qt::AlignRight,
739 which maps to the horizontal scroll bar, or Qt::AlignTop and
740 Qt::AlignBottom, which maps to the vertical scroll bar.
741
742 A scroll bar widget can be removed by either re-parenting the
743 widget or deleting it. It's also possible to hide a widget with
744 QWidget::hide()
745
746 The scroll bar widget will be resized to fit the scroll bar
747 geometry for the current style. The following describes the case
748 for scroll bar widgets on the horizontal scroll bar:
749
750 The height of the widget will be set to match the height of the
751 scroll bar. To control the width of the widget, use
752 QWidget::setMinimumWidth and QWidget::setMaximumWidth, or
753 implement QWidget::sizeHint() and set a horizontal size policy.
754 If you want a square widget, call
755 QStyle::pixelMetric(QStyle::PM_ScrollBarExtent) and set the
756 width to this value.
757
758 \sa scrollBarWidgets()
759*/
760void QAbstractScrollArea::addScrollBarWidget(QWidget *widget, Qt::Alignment alignment)
761{
762 Q_D(QAbstractScrollArea);
763
764 if (widget == nullptr)
765 return;
766
767 const Qt::Orientation scrollBarOrientation
768 = ((alignment & Qt::AlignLeft) || (alignment & Qt::AlignRight)) ? Qt::Horizontal : Qt::Vertical;
769 const QAbstractScrollAreaScrollBarContainer::LogicalPosition position
770 = ((alignment & Qt::AlignRight) || (alignment & Qt::AlignBottom))
771 ? QAbstractScrollAreaScrollBarContainer::LogicalRight : QAbstractScrollAreaScrollBarContainer::LogicalLeft;
772 d->scrollBarContainers[scrollBarOrientation]->addWidget(widget, position);
773 d->layoutChildren();
774 if (isHidden() == false)
775 widget->show();
776}
777
778/*!
779 \since 4.2
780 Returns a list of the currently set scroll bar widgets. \a alignment
781 can be any combination of the four location flags.
782
783 \sa addScrollBarWidget()
784*/
785QWidgetList QAbstractScrollArea::scrollBarWidgets(Qt::Alignment alignment)
786{
787 Q_D(QAbstractScrollArea);
788
789 QWidgetList list;
790
791 if (alignment & Qt::AlignLeft)
792 list += d->scrollBarContainers[Qt::Horizontal]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalLeft);
793 if (alignment & Qt::AlignRight)
794 list += d->scrollBarContainers[Qt::Horizontal]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalRight);
795 if (alignment & Qt::AlignTop)
796 list += d->scrollBarContainers[Qt::Vertical]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalLeft);
797 if (alignment & Qt::AlignBottom)
798 list += d->scrollBarContainers[Qt::Vertical]->widgets(QAbstractScrollAreaScrollBarContainer::LogicalRight);
799
800 return list;
801}
802
803/*!
804 Sets the margins around the scrolling area to \a left, \a top, \a
805 right and \a bottom. This is useful for applications such as
806 spreadsheets with "locked" rows and columns. The marginal space
807 is left blank; put widgets in the unused area.
808
809 Note that this function is frequently called by QTreeView and
810 QTableView, so margins must be implemented by QAbstractScrollArea
811 subclasses. Also, if the subclasses are to be used in item views,
812 they should not call this function.
813
814 By default all margins are zero.
815 \sa viewportMargins()
816*/
817void QAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
818{
819 Q_D(QAbstractScrollArea);
820 d->left = left;
821 d->top = top;
822 d->right = right;
823 d->bottom = bottom;
824 d->layoutChildren();
825}
826
827/*!
828 \since 4.6
829 Sets \a margins around the scrolling area. This is useful for
830 applications such as spreadsheets with "locked" rows and columns.
831 The marginal space is is left blank; put widgets in the unused
832 area.
833
834 By default all margins are zero.
835 \sa viewportMargins()
836*/
837void QAbstractScrollArea::setViewportMargins(const QMargins &margins)
838{
839 setViewportMargins(margins.left(), margins.top(),
840 margins.right(), margins.bottom());
841}
842
843/*!
844 \since 5.5
845 Returns the margins around the scrolling area.
846 By default all the margins are zero.
847
848 \sa setViewportMargins()
849*/
850QMargins QAbstractScrollArea::viewportMargins() const
851{
852 Q_D(const QAbstractScrollArea);
853 return QMargins(d->left, d->top, d->right, d->bottom);
854}
855
856/*! \internal */
857bool QAbstractScrollArea::eventFilter(QObject *o, QEvent *e)
858{
859 Q_D(QAbstractScrollArea);
860 if ((o == d->hbar || o == d->vbar) && (e->type() == QEvent::HoverEnter || e->type() == QEvent::HoverLeave)) {
861 if (d->hbarpolicy == Qt::ScrollBarAsNeeded && d->vbarpolicy == Qt::ScrollBarAsNeeded) {
862 QScrollBar *sbar = static_cast<QScrollBar*>(o);
863 QScrollBar *sibling = sbar == d->hbar ? d->vbar : d->hbar;
864 if (sbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, sbar) &&
865 sibling->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, sibling))
866 d->setScrollBarTransient(sibling, e->type() == QEvent::HoverLeave);
867 }
868 }
869 return QFrame::eventFilter(o, e);
870}
871
872/*!
873 \fn bool QAbstractScrollArea::event(QEvent *event)
874
875 \reimp
876
877 This is the main event handler for the QAbstractScrollArea widget (\e not
878 the scrolling area viewport()). The specified \a event is a general event
879 object that may need to be cast to the appropriate class depending on its
880 type.
881
882 \sa QEvent::type()
883*/
884bool QAbstractScrollArea::event(QEvent *e)
885{
886 Q_D(QAbstractScrollArea);
887 switch (e->type()) {
888 case QEvent::AcceptDropsChange:
889 // There was a chance that with accessibility client we get an
890 // event before the viewport was created.
891 // Also, in some cases we might get here from QWidget::event() virtual function which is (indirectly) called
892 // from the viewport constructor at the time when the d->viewport is not yet initialized even without any
893 // accessibility client. See qabstractscrollarea autotest for a test case.
894 if (d->viewport)
895 d->viewport->setAcceptDrops(acceptDrops());
896 break;
897 case QEvent::MouseTrackingChange:
898 d->viewport->setMouseTracking(hasMouseTracking());
899 break;
900 case QEvent::Resize:
901 if (!d->inResize) {
902 d->inResize = true;
903 d->layoutChildren();
904 d->inResize = false;
905 }
906 break;
907 case QEvent::Show:
908 if (!d->shownOnce && d->sizeAdjustPolicy == QAbstractScrollArea::AdjustToContentsOnFirstShow) {
909 d->sizeHint = QSize();
910 updateGeometry();
911 }
912 d->shownOnce = true;
913 return QFrame::event(e);
914 case QEvent::Paint: {
915 QStyleOption option;
916 option.initFrom(this);
917 if (d->cornerPaintingRect.isValid()) {
918 option.rect = d->cornerPaintingRect;
919 QPainter p(this);
920 style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, &option, &p, this);
921 }
922 }
923 QFrame::paintEvent((QPaintEvent*)e);
924 break;
925#ifndef QT_NO_CONTEXTMENU
926 case QEvent::ContextMenu:
927 if (static_cast<QContextMenuEvent *>(e)->reason() == QContextMenuEvent::Keyboard)
928 return QFrame::event(e);
929 e->ignore();
930 break;
931#endif // QT_NO_CONTEXTMENU
932 case QEvent::MouseButtonPress:
933 case QEvent::MouseButtonRelease:
934 case QEvent::MouseButtonDblClick:
935 case QEvent::MouseMove:
936 case QEvent::Wheel:
937#if QT_CONFIG(draganddrop)
938 case QEvent::Drop:
939 case QEvent::DragEnter:
940 case QEvent::DragMove:
941 case QEvent::DragLeave:
942#endif
943 // ignore touch events in case they have been propagated from the viewport
944 case QEvent::TouchBegin:
945 case QEvent::TouchUpdate:
946 case QEvent::TouchEnd:
947 return false;
948#ifndef QT_NO_GESTURES
949 case QEvent::Gesture:
950 {
951 QGestureEvent *ge = static_cast<QGestureEvent *>(e);
952 QPanGesture *g = static_cast<QPanGesture *>(ge->gesture(Qt::PanGesture));
953 if (g) {
954 QScrollBar *hBar = horizontalScrollBar();
955 QScrollBar *vBar = verticalScrollBar();
956 QPointF delta = g->delta();
957 if (!delta.isNull()) {
958 if (QGuiApplication::isRightToLeft())
959 delta.rx() *= -1;
960 int newX = hBar->value() - delta.x();
961 int newY = vBar->value() - delta.y();
962 hBar->setValue(newX);
963 vBar->setValue(newY);
964 }
965 return true;
966 }
967 return false;
968 }
969#endif // QT_NO_GESTURES
970 case QEvent::ScrollPrepare:
971 {
972 QScrollPrepareEvent *se = static_cast<QScrollPrepareEvent *>(e);
973 if (d->canStartScrollingAt(se->startPos().toPoint())) {
974 QScrollBar *hBar = horizontalScrollBar();
975 QScrollBar *vBar = verticalScrollBar();
976
977 se->setViewportSize(QSizeF(viewport()->size()));
978 se->setContentPosRange(QRectF(0, 0, hBar->maximum(), vBar->maximum()));
979 se->setContentPos(QPointF(hBar->value(), vBar->value()));
980 se->accept();
981 return true;
982 }
983 return false;
984 }
985 case QEvent::Scroll:
986 {
987 QScrollEvent *se = static_cast<QScrollEvent *>(e);
988
989 QScrollBar *hBar = horizontalScrollBar();
990 QScrollBar *vBar = verticalScrollBar();
991 hBar->setValue(se->contentPos().x());
992 vBar->setValue(se->contentPos().y());
993
994 QPoint delta = d->overshoot - se->overshootDistance().toPoint();
995 if (!delta.isNull())
996 viewport()->move(viewport()->pos() + delta);
997
998 d->overshoot = se->overshootDistance().toPoint();
999
1000 return true;
1001 }
1002 case QEvent::StyleChange:
1003 case QEvent::LayoutDirectionChange:
1004 case QEvent::ApplicationLayoutDirectionChange:
1005 case QEvent::LayoutRequest:
1006 d->layoutChildren();
1007 Q_FALLTHROUGH();
1008 default:
1009 return QFrame::event(e);
1010 }
1011 return true;
1012}
1013
1014/*!
1015 \fn bool QAbstractScrollArea::viewportEvent(QEvent *event)
1016
1017 The main event handler for the scrolling area (the viewport() widget).
1018 It handles the \a event specified, and can be called by subclasses to
1019 provide reasonable default behavior.
1020
1021 Returns \c true to indicate to the event system that the event has been
1022 handled, and needs no further processing; otherwise returns \c false to
1023 indicate that the event should be propagated further.
1024
1025 You can reimplement this function in a subclass, but we recommend
1026 using one of the specialized event handlers instead.
1027
1028 Specialized handlers for viewport events are: paintEvent(),
1029 mousePressEvent(), mouseReleaseEvent(), mouseDoubleClickEvent(),
1030 mouseMoveEvent(), wheelEvent(), dragEnterEvent(), dragMoveEvent(),
1031 dragLeaveEvent(), dropEvent(), contextMenuEvent(), and
1032 resizeEvent().
1033*/
1034bool QAbstractScrollArea::viewportEvent(QEvent *e)
1035{
1036 switch (e->type()) {
1037 case QEvent::Resize:
1038 case QEvent::Paint:
1039 case QEvent::MouseButtonPress:
1040 case QEvent::MouseButtonRelease:
1041 case QEvent::MouseButtonDblClick:
1042 case QEvent::TouchBegin:
1043 case QEvent::TouchUpdate:
1044 case QEvent::TouchEnd:
1045 case QEvent::MouseMove:
1046 case QEvent::ContextMenu:
1047#if QT_CONFIG(wheelevent)
1048 case QEvent::Wheel:
1049#endif
1050#if QT_CONFIG(draganddrop)
1051 case QEvent::Drop:
1052 case QEvent::DragEnter:
1053 case QEvent::DragMove:
1054 case QEvent::DragLeave:
1055#endif
1056#ifndef QT_NO_OPENGL
1057 // QOpenGLWidget needs special support because it has to know
1058 // its size has changed, so that it can resize its fbo.
1059 if (e->type() == QEvent::Resize)
1060 QWidgetPrivate::get(viewport())->resizeViewportFramebuffer();
1061#endif
1062 return QFrame::event(e);
1063 case QEvent::LayoutRequest:
1064#ifndef QT_NO_GESTURES
1065 case QEvent::Gesture:
1066 case QEvent::GestureOverride:
1067 return event(e);
1068#endif
1069 case QEvent::ScrollPrepare:
1070 case QEvent::Scroll:
1071 return event(e);
1072 default:
1073 break;
1074 }
1075 return false; // let the viewport widget handle the event
1076}
1077
1078/*!
1079 \fn void QAbstractScrollArea::resizeEvent(QResizeEvent *event)
1080
1081 This event handler can be reimplemented in a subclass to receive
1082 resize events (passed in \a event), for the viewport() widget.
1083
1084 When resizeEvent() is called, the viewport already has its new
1085 geometry: Its new size is accessible through the
1086 QResizeEvent::size() function, and the old size through
1087 QResizeEvent::oldSize().
1088
1089 \sa QWidget::resizeEvent()
1090 */
1091void QAbstractScrollArea::resizeEvent(QResizeEvent *)
1092{
1093}
1094
1095/*!
1096 \fn void QAbstractScrollArea::paintEvent(QPaintEvent *event)
1097
1098 This event handler can be reimplemented in a subclass to receive
1099 paint events (passed in \a event), for the viewport() widget.
1100
1101 \note If you create a QPainter, it must operate on the viewport().
1102
1103 \sa QWidget::paintEvent()
1104*/
1105void QAbstractScrollArea::paintEvent(QPaintEvent*)
1106{
1107}
1108
1109/*!
1110 This event handler can be reimplemented in a subclass to receive
1111 mouse press events for the viewport() widget. The event is passed
1112 in \a e.
1113
1114 The default implementation calls QWidget::mousePressEvent() for
1115 default popup handling.
1116
1117 \sa QWidget::mousePressEvent()
1118*/
1119void QAbstractScrollArea::mousePressEvent(QMouseEvent *e)
1120{
1121 QWidget::mousePressEvent(e);
1122}
1123
1124/*!
1125 This event handler can be reimplemented in a subclass to receive
1126 mouse release events for the viewport() widget. The event is
1127 passed in \a e.
1128
1129 \sa QWidget::mouseReleaseEvent()
1130*/
1131void QAbstractScrollArea::mouseReleaseEvent(QMouseEvent *e)
1132{
1133 e->ignore();
1134}
1135
1136/*!
1137 This event handler can be reimplemented in a subclass to receive
1138 mouse double click events for the viewport() widget. The event is
1139 passed in \a e.
1140
1141 \sa QWidget::mouseDoubleClickEvent()
1142*/
1143void QAbstractScrollArea::mouseDoubleClickEvent(QMouseEvent *e)
1144{
1145 e->ignore();
1146}
1147
1148/*!
1149 This event handler can be reimplemented in a subclass to receive
1150 mouse move events for the viewport() widget. The event is passed
1151 in \a e.
1152
1153 \sa QWidget::mouseMoveEvent()
1154*/
1155void QAbstractScrollArea::mouseMoveEvent(QMouseEvent *e)
1156{
1157 e->ignore();
1158}
1159
1160/*!
1161 This event handler can be reimplemented in a subclass to receive
1162 wheel events for the viewport() widget. The event is passed in \a
1163 e.
1164
1165 \sa QWidget::wheelEvent()
1166*/
1167#if QT_CONFIG(wheelevent)
1168void QAbstractScrollArea::wheelEvent(QWheelEvent *e)
1169{
1170 Q_D(QAbstractScrollArea);
1171 if (qAbs(e->angleDelta().x()) > qAbs(e->angleDelta().y()))
1172 QCoreApplication::sendEvent(d->hbar, e);
1173 else
1174 QCoreApplication::sendEvent(d->vbar, e);
1175}
1176#endif
1177
1178#ifndef QT_NO_CONTEXTMENU
1179/*!
1180 This event handler can be reimplemented in a subclass to receive
1181 context menu events for the viewport() widget. The event is passed
1182 in \a e.
1183
1184 \sa QWidget::contextMenuEvent()
1185*/
1186void QAbstractScrollArea::contextMenuEvent(QContextMenuEvent *e)
1187{
1188 e->ignore();
1189}
1190#endif // QT_NO_CONTEXTMENU
1191
1192/*!
1193 This function is called with key event \a e when key presses
1194 occur. It handles PageUp, PageDown, Up, Down, Left, and Right, and
1195 ignores all other key presses.
1196*/
1197void QAbstractScrollArea::keyPressEvent(QKeyEvent * e)
1198{
1199 Q_D(QAbstractScrollArea);
1200 if (false){
1201#ifndef QT_NO_SHORTCUT
1202 } else if (e == QKeySequence::MoveToPreviousPage) {
1203 d->vbar->triggerAction(QScrollBar::SliderPageStepSub);
1204 } else if (e == QKeySequence::MoveToNextPage) {
1205 d->vbar->triggerAction(QScrollBar::SliderPageStepAdd);
1206#endif
1207 } else {
1208 switch (e->key()) {
1209 case Qt::Key_Up:
1210 d->vbar->triggerAction(QScrollBar::SliderSingleStepSub);
1211 break;
1212 case Qt::Key_Down:
1213 d->vbar->triggerAction(QScrollBar::SliderSingleStepAdd);
1214 break;
1215 case Qt::Key_Left:
1216 d->hbar->triggerAction(
1217 layoutDirection() == Qt::LeftToRight
1218 ? QScrollBar::SliderSingleStepSub : QScrollBar::SliderSingleStepAdd);
1219 break;
1220 case Qt::Key_Right:
1221 d->hbar->triggerAction(
1222 layoutDirection() == Qt::LeftToRight
1223 ? QScrollBar::SliderSingleStepAdd : QScrollBar::SliderSingleStepSub);
1224 break;
1225 default:
1226 e->ignore();
1227 return;
1228 }
1229 }
1230 e->accept();
1231}
1232
1233
1234#if QT_CONFIG(draganddrop)
1235/*!
1236 \fn void QAbstractScrollArea::dragEnterEvent(QDragEnterEvent *event)
1237
1238 This event handler can be reimplemented in a subclass to receive
1239 drag enter events (passed in \a event), for the viewport() widget.
1240
1241 \sa QWidget::dragEnterEvent()
1242*/
1243void QAbstractScrollArea::dragEnterEvent(QDragEnterEvent *)
1244{
1245}
1246
1247/*!
1248 \fn void QAbstractScrollArea::dragMoveEvent(QDragMoveEvent *event)
1249
1250 This event handler can be reimplemented in a subclass to receive
1251 drag move events (passed in \a event), for the viewport() widget.
1252
1253 \sa QWidget::dragMoveEvent()
1254*/
1255void QAbstractScrollArea::dragMoveEvent(QDragMoveEvent *)
1256{
1257}
1258
1259/*!
1260 \fn void QAbstractScrollArea::dragLeaveEvent(QDragLeaveEvent *event)
1261
1262 This event handler can be reimplemented in a subclass to receive
1263 drag leave events (passed in \a event), for the viewport() widget.
1264
1265 \sa QWidget::dragLeaveEvent()
1266*/
1267void QAbstractScrollArea::dragLeaveEvent(QDragLeaveEvent *)
1268{
1269}
1270
1271/*!
1272 \fn void QAbstractScrollArea::dropEvent(QDropEvent *event)
1273
1274 This event handler can be reimplemented in a subclass to receive
1275 drop events (passed in \a event), for the viewport() widget.
1276
1277 \sa QWidget::dropEvent()
1278*/
1279void QAbstractScrollArea::dropEvent(QDropEvent *)
1280{
1281}
1282
1283
1284#endif
1285
1286/*!
1287 This virtual handler is called when the scroll bars are moved by
1288 \a dx, \a dy, and consequently the viewport's contents should be
1289 scrolled accordingly.
1290
1291 The default implementation simply calls update() on the entire
1292 viewport(), subclasses can reimplement this handler for
1293 optimization purposes, or - like QScrollArea - to move a contents
1294 widget. The parameters \a dx and \a dy are there for convenience,
1295 so that the class knows how much should be scrolled (useful
1296 e.g. when doing pixel-shifts). You may just as well ignore these
1297 values and scroll directly to the position the scroll bars
1298 indicate.
1299
1300 Calling this function in order to scroll programmatically is an
1301 error, use the scroll bars instead (e.g. by calling
1302 QScrollBar::setValue() directly).
1303*/
1304void QAbstractScrollArea::scrollContentsBy(int, int)
1305{
1306 viewport()->update();
1307}
1308
1309bool QAbstractScrollAreaPrivate::canStartScrollingAt(const QPoint &startPos) const
1310{
1311 Q_Q(const QAbstractScrollArea);
1312
1313 // don't start scrolling on a QAbstractSlider
1314 if (qobject_cast<QAbstractSlider *>(q->viewport()->childAt(startPos)))
1315 return false;
1316
1317 return true;
1318}
1319
1320void QAbstractScrollAreaPrivate::flashScrollBars()
1321{
1322 QStyleOptionSlider opt;
1323 hbar->initStyleOption(&opt);
1324
1325 bool htransient = hbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, hbar);
1326 if ((hbarpolicy != Qt::ScrollBarAlwaysOff) && (hbarpolicy == Qt::ScrollBarAsNeeded || htransient))
1327 hbar->d_func()->flash();
1328 vbar->initStyleOption(&opt);
1329 bool vtransient = vbar->style()->styleHint(QStyle::SH_ScrollBar_Transient, &opt, vbar);
1330 if ((vbarpolicy != Qt::ScrollBarAlwaysOff) && (vbarpolicy == Qt::ScrollBarAsNeeded || vtransient))
1331 vbar->d_func()->flash();
1332}
1333
1334void QAbstractScrollAreaPrivate::setScrollBarTransient(QScrollBar *scrollBar, bool transient)
1335{
1336 scrollBar->d_func()->setTransient(transient);
1337}
1338
1339void QAbstractScrollAreaPrivate::_q_hslide(int x)
1340{
1341 Q_Q(QAbstractScrollArea);
1342 int dx = xoffset - x;
1343 xoffset = x;
1344 q->scrollContentsBy(dx, 0);
1345 flashScrollBars();
1346}
1347
1348void QAbstractScrollAreaPrivate::_q_vslide(int y)
1349{
1350 Q_Q(QAbstractScrollArea);
1351 int dy = yoffset - y;
1352 yoffset = y;
1353 q->scrollContentsBy(0, dy);
1354 flashScrollBars();
1355}
1356
1357void QAbstractScrollAreaPrivate::_q_showOrHideScrollBars()
1358{
1359 layoutChildren();
1360}
1361
1362QPoint QAbstractScrollAreaPrivate::contentsOffset() const
1363{
1364 Q_Q(const QAbstractScrollArea);
1365 QPoint offset;
1366 if (vbar->isVisible())
1367 offset.setY(vbar->value());
1368 if (hbar->isVisible()) {
1369 if (q->isRightToLeft())
1370 offset.setX(hbar->maximum() - hbar->value());
1371 else
1372 offset.setX(hbar->value());
1373 }
1374 return offset;
1375}
1376
1377/*!
1378 \reimp
1379
1380*/
1381QSize QAbstractScrollArea::minimumSizeHint() const
1382{
1383 Q_D(const QAbstractScrollArea);
1384 int hsbExt = d->hbar->sizeHint().height();
1385 int vsbExt = d->vbar->sizeHint().width();
1386 int extra = 2 * d->frameWidth;
1387 QStyleOption opt;
1388 opt.initFrom(this);
1389 if ((d->frameStyle != QFrame::NoFrame)
1390 && style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, this)) {
1391 extra += style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, this);
1392 }
1393 return QSize(d->scrollBarContainers[Qt::Horizontal]->sizeHint().width() + vsbExt + extra,
1394 d->scrollBarContainers[Qt::Vertical]->sizeHint().height() + hsbExt + extra);
1395}
1396
1397/*!
1398 Returns the sizeHint property of the scroll area. The size is determined by using
1399 viewportSizeHint() plus some extra space for scroll bars, if needed.
1400 \reimp
1401*/
1402QSize QAbstractScrollArea::sizeHint() const
1403{
1404 Q_D(const QAbstractScrollArea);
1405 if (d->sizeAdjustPolicy == QAbstractScrollArea::AdjustIgnored)
1406 return QSize(256, 192);
1407
1408 if (!d->sizeHint.isValid() || d->sizeAdjustPolicy == QAbstractScrollArea::AdjustToContents) {
1409 const int f = 2 * d->frameWidth;
1410 const QSize frame(f, f);
1411 const bool vbarHidden = !d->vbar->isVisibleTo(this) || d->vbarpolicy == Qt::ScrollBarAlwaysOff;
1412 const bool hbarHidden = !d->hbar->isVisibleTo(this) || d->hbarpolicy == Qt::ScrollBarAlwaysOff;
1413 const QSize scrollbars(vbarHidden ? 0 : d->vbar->sizeHint().width(),
1414 hbarHidden ? 0 : d->hbar->sizeHint().height());
1415 d->sizeHint = frame + scrollbars + viewportSizeHint();
1416 }
1417 return d->sizeHint;
1418}
1419
1420/*!
1421 \since 5.2
1422 Returns the recommended size for the viewport.
1423 The default implementation returns viewport()->sizeHint().
1424 Note that the size is just the viewport's size, without any scroll bars visible.
1425 */
1426QSize QAbstractScrollArea::viewportSizeHint() const
1427{
1428 Q_D(const QAbstractScrollArea);
1429 if (d->viewport) {
1430 const QSize sh = d->viewport->sizeHint();
1431 if (sh.isValid()) {
1432 return sh;
1433 }
1434 }
1435 const int h = qMax(10, fontMetrics().height());
1436 return QSize(6 * h, 4 * h);
1437}
1438
1439/*!
1440 \since 5.2
1441 \property QAbstractScrollArea::sizeAdjustPolicy
1442 \brief the policy describing how the size of the scroll area changes when the
1443 size of the viewport changes.
1444
1445 The default policy is QAbstractScrollArea::AdjustIgnored.
1446 Changing this property might actually resize the scrollarea.
1447*/
1448
1449QAbstractScrollArea::SizeAdjustPolicy QAbstractScrollArea::sizeAdjustPolicy() const
1450{
1451 Q_D(const QAbstractScrollArea);
1452 return d->sizeAdjustPolicy;
1453}
1454
1455void QAbstractScrollArea::setSizeAdjustPolicy(SizeAdjustPolicy policy)
1456{
1457 Q_D(QAbstractScrollArea);
1458 if (d->sizeAdjustPolicy == policy)
1459 return;
1460
1461 d->sizeAdjustPolicy = policy;
1462 d->sizeHint = QSize();
1463 updateGeometry();
1464}
1465
1466/*!
1467 This slot is called by QAbstractScrollArea after setViewport(\a
1468 viewport) has been called. Reimplement this function in a
1469 subclass of QAbstractScrollArea to initialize the new \a viewport
1470 before it is used.
1471
1472 \sa setViewport()
1473*/
1474void QAbstractScrollArea::setupViewport(QWidget *viewport)
1475{
1476 Q_UNUSED(viewport);
1477}
1478
1479int QAbstractScrollAreaPrivate::defaultSingleStep() const
1480{
1481 auto *platformTheme = QGuiApplicationPrivate::platformTheme();
1482 return platformTheme->themeHint(QPlatformTheme::ScrollSingleStepDistance).value<int>();
1483}
1484
1485QT_END_NAMESPACE
1486
1487#include "moc_qabstractscrollarea.cpp"
1488#include "moc_qabstractscrollarea_p.cpp"
1489
1490#endif // QT_CONFIG(scrollarea)