1 | // Copyright (C) 2016 The Qt Company Ltd. |
---|---|
2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause |
3 | |
4 | #include <QtWidgets> |
5 | |
6 | class MyScrollArea : public QAbstractScrollArea |
7 | { |
8 | public: |
9 | MyScrollArea(QWidget *w); |
10 | void setWidget(QWidget *w); |
11 | |
12 | protected: |
13 | void scrollContentsBy(int dx, int dy) override; |
14 | void resizeEvent(QResizeEvent *event) override; |
15 | |
16 | private: |
17 | void updateWidgetPosition(); |
18 | void updateArea(); |
19 | |
20 | QWidget *widget; |
21 | }; |
22 | |
23 | MyScrollArea::MyScrollArea(QWidget *widget) |
24 | : QAbstractScrollArea() |
25 | { |
26 | setWidget(widget); |
27 | } |
28 | |
29 | void MyScrollArea::setWidget(QWidget *w) |
30 | { |
31 | widget = w; |
32 | widget->setParent(viewport()); |
33 | if (!widget->testAttribute(attribute: Qt::WA_Resized)) |
34 | widget->resize(widget->sizeHint()); |
35 | |
36 | verticalScrollBar()->setValue(0); |
37 | verticalScrollBar()->setValue(0); |
38 | |
39 | updateArea(); |
40 | } |
41 | |
42 | void MyScrollArea::updateWidgetPosition() |
43 | { |
44 | //! [0] |
45 | int hvalue = horizontalScrollBar()->value(); |
46 | int vvalue = verticalScrollBar()->value(); |
47 | QPoint topLeft = viewport()->rect().topLeft(); |
48 | |
49 | widget->move(ax: topLeft.x() - hvalue, ay: topLeft.y() - vvalue); |
50 | //! [0] |
51 | } |
52 | |
53 | void MyScrollArea::scrollContentsBy(int dx, int dy) |
54 | { |
55 | Q_UNUSED(dx); |
56 | Q_UNUSED(dy); |
57 | updateWidgetPosition(); |
58 | } |
59 | |
60 | void MyScrollArea::updateArea() |
61 | { |
62 | //! [1] |
63 | QSize areaSize = viewport()->size(); |
64 | QSize widgetSize = widget->size(); |
65 | |
66 | verticalScrollBar()->setPageStep(areaSize.height()); |
67 | horizontalScrollBar()->setPageStep(areaSize.width()); |
68 | verticalScrollBar()->setRange(min: 0, max: widgetSize.height() - areaSize.height()); |
69 | horizontalScrollBar()->setRange(min: 0, max: widgetSize.width() - areaSize.width()); |
70 | updateWidgetPosition(); |
71 | //! [1] |
72 | } |
73 | |
74 | void MyScrollArea::resizeEvent(QResizeEvent *event) |
75 | { |
76 | Q_UNUSED(event); |
77 | updateArea(); |
78 | } |
79 |