1 | /* |
2 | * SPDX-FileCopyrightText: 2020 Carson Black <uhhadd@gmail.com> |
3 | * |
4 | * SPDX-License-Identifier: LGPL-2.0-or-later |
5 | */ |
6 | |
7 | #pragma once |
8 | |
9 | #include <QMap> |
10 | #include <QObject> |
11 | #include <QPair> |
12 | #include <QPointer> |
13 | #include <QQmlListProperty> |
14 | #include <QQmlParserStatus> |
15 | #include <QQuickItem> |
16 | |
17 | /** |
18 | * SizeGroup is a utility object that makes groups of items request the same size. |
19 | */ |
20 | class SizeGroup : public QObject, public QQmlParserStatus |
21 | { |
22 | Q_OBJECT |
23 | QML_ELEMENT |
24 | Q_INTERFACES(QQmlParserStatus) |
25 | |
26 | public: |
27 | enum Mode { |
28 | None = 0, /// SizeGroup does nothing |
29 | Width = 1, /// SizeGroup syncs item widths |
30 | Height = 2, /// SizeGroup syncs item heights |
31 | Both = 3, /// SizeGroup syncs both item widths and heights |
32 | }; |
33 | Q_ENUM(Mode) |
34 | Q_DECLARE_FLAGS(Modes, Mode) |
35 | |
36 | private: |
37 | Mode m_mode = None; |
38 | QList<QPointer<QQuickItem>> m_items; |
39 | QMap<QQuickItem *, QPair<QMetaObject::Connection, QMetaObject::Connection>> m_connections; |
40 | |
41 | public: |
42 | /** |
43 | * Which dimensions this SizeGroup should adjust |
44 | */ |
45 | Q_PROPERTY(Mode mode MEMBER m_mode NOTIFY modeChanged FINAL) |
46 | Q_SIGNAL void modeChanged(); |
47 | |
48 | /** |
49 | * Which items this SizeGroup should adjust |
50 | */ |
51 | Q_PROPERTY(QQmlListProperty<QQuickItem> items READ items CONSTANT FINAL) |
52 | QQmlListProperty<QQuickItem> items(); |
53 | |
54 | void adjustItems(Mode whatChanged); |
55 | void connectItem(QQuickItem *item); |
56 | |
57 | /** |
58 | * Forces the SizeGroup to relayout items. |
59 | * |
60 | * Normally this is never needed as the SizeGroup automatically |
61 | * relayout items as they're added and their sizes change. |
62 | */ |
63 | Q_INVOKABLE void relayout(); |
64 | |
65 | void classBegin() override |
66 | { |
67 | } |
68 | void componentComplete() override; |
69 | |
70 | private: |
71 | static void appendItem(QQmlListProperty<QQuickItem> *prop, QQuickItem *value); |
72 | static qsizetype itemCount(QQmlListProperty<QQuickItem> *prop); |
73 | static QQuickItem *itemAt(QQmlListProperty<QQuickItem> *prop, qsizetype index); |
74 | static void clearItems(QQmlListProperty<QQuickItem> *prop); |
75 | }; |
76 | |