File: kcollapsiblegroupbox.cpp

package info (click to toggle)
kwidgetsaddons 5.28.0-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 62,388 kB
  • ctags: 3,611
  • sloc: cpp: 26,647; python: 682; sh: 23; makefile: 6
file content (336 lines) | stat: -rw-r--r-- 9,635 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * This file is part of the KDE project
 * Copyright (C) 2015 David Edmundson <davidedmundson@kde.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "kcollapsiblegroupbox.h"

#include <QLayout>
#include <QStyle>
#include <QPainter>
#include <QStyleOption>
#include <QAction>
#include <QDebug>
#include <QTimeLine>
#include <QMouseEvent>

class KCollapsibleGroupBoxPrivate {
public:
    KCollapsibleGroupBoxPrivate(KCollapsibleGroupBox *q);
    void updateChildrenVisibility(bool visible);
    void recalculateHeaderSize();
    QSize contentSize() const;
    QSize contentMinimumSize() const;

    KCollapsibleGroupBox *q;
    QTimeLine *animation;
    QString title;
    bool isExpanded;
    bool headerContainsMouse;
    QSize headerSize;
    int shortcutId;

};

KCollapsibleGroupBoxPrivate::KCollapsibleGroupBoxPrivate(KCollapsibleGroupBox* q):
    q(q),
    isExpanded(false),
    headerContainsMouse(false),
    shortcutId(0)
{}

KCollapsibleGroupBox::KCollapsibleGroupBox(QWidget* parent):
    QWidget(parent),
    d(new KCollapsibleGroupBoxPrivate(this))
{
    d->recalculateHeaderSize();

    d->animation = new QTimeLine(500, this); //duration matches kmessagewidget
    connect(d->animation, &QTimeLine::valueChanged, this, [this](qreal value) {
        setFixedHeight((d->contentSize().height() * value) + d->headerSize.height());
    });
    connect(d->animation, &QTimeLine::stateChanged, this, [this](QTimeLine::State state) {
        if (state == QTimeLine::NotRunning) {
            //when collapsed hide contents to save resources and more importantly get it out the focus chain
            d->updateChildrenVisibility(d->isExpanded);
        }
    });

    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
    setFocusPolicy(Qt::TabFocus);
    setMouseTracking(true);
}

KCollapsibleGroupBox::~KCollapsibleGroupBox()
{
    if (d->animation->state() == QTimeLine::Running) {
        d->animation->stop();
    }
    delete d;
}

void KCollapsibleGroupBox::setTitle(const QString& title)
{
    d->title = title;
    d->recalculateHeaderSize();

    update();
    updateGeometry();

    if (d->shortcutId) {
        releaseShortcut(d->shortcutId);
    }

    d->shortcutId = grabShortcut(QKeySequence::mnemonic(title));

    setAccessibleName(title);

    emit titleChanged();
}

QString KCollapsibleGroupBox::title() const
{
    return d->title;
}

void KCollapsibleGroupBox::setExpanded(bool expanded)
{
    if (expanded == d->isExpanded) {
        return;
    }

    d->isExpanded = expanded;
    emit expandedChanged();

    d->updateChildrenVisibility(true);

    d->animation->setDirection(expanded ? QTimeLine::Forward : QTimeLine::Backward);
    d->animation->start();

    //when going from collapsed to expanded changing the child visibility calls an updateGeometry
    //which calls sizeHint with expanded true before the first frame of the animation kicks in
    //trigger an effective frame 0
    if (expanded) {
        setFixedHeight(d->headerSize.height());
    }
}

bool KCollapsibleGroupBox::isExpanded() const
{
    return d->isExpanded;
}

void KCollapsibleGroupBox::collapse()
{
    setExpanded(false);
}

void KCollapsibleGroupBox::expand()
{
    setExpanded(true);
}

void KCollapsibleGroupBox::toggle()
{
    setExpanded(!d->isExpanded);
}

void KCollapsibleGroupBox::paintEvent(QPaintEvent *event)
{
    QPainter p(this);

    QStyleOptionButton baseOption;
    baseOption.initFrom(this);
    baseOption.rect = QRect(0, 0, width(), d->headerSize.height());
    baseOption.text = d->title;

    if (d->headerContainsMouse) {
        baseOption.state |= QStyle::State_MouseOver;
    }

    QStyle::PrimitiveElement element;
    if (d->isExpanded) {
        element = QStyle::PE_IndicatorArrowDown;
    } else {
        element = isLeftToRight() ? QStyle::PE_IndicatorArrowRight : QStyle::PE_IndicatorArrowLeft;
    }

    QStyleOptionButton indicatorOption = baseOption;
    indicatorOption.rect = style()->subElementRect(QStyle::SE_CheckBoxIndicator, &indicatorOption, this);
    style()->drawPrimitive(element, &indicatorOption, &p, this);

    QStyleOptionButton labelOption = baseOption;
    labelOption.rect = style()->subElementRect(QStyle::SE_CheckBoxContents, &labelOption, this);
    style()->drawControl(QStyle::CE_CheckBoxLabel, &labelOption, &p, this);

    Q_UNUSED(event)
}

QSize KCollapsibleGroupBox::sizeHint() const
{
    if (d->isExpanded) {
        return d->contentSize() + QSize(0, d->headerSize.height());
    } else {
        return QSize(d->contentSize().width(), d->headerSize.height());
    }
}

QSize KCollapsibleGroupBox::minimumSizeHint() const
{
    int minimumWidth = qMax(d->contentSize().width(), d->headerSize.width());
    return QSize(minimumWidth, d->headerSize.height());
}

bool KCollapsibleGroupBox::event(QEvent *event)
{
    switch (event->type()) {
        case QEvent::StyleChange:
            /*fall through*/
        case QEvent::FontChange:
            d->recalculateHeaderSize();
            break;
        case QEvent::Shortcut:
        {
            QShortcutEvent *se = static_cast<QShortcutEvent*>(event);
            if(d->shortcutId == se->shortcutId()) {
                toggle();
                return true;
            }
            break;
        }
        case QEvent::ChildAdded:
        {
            QChildEvent *ce = static_cast<QChildEvent*>(event);
            if (ce->child()->isWidgetType()) {
                static_cast<QWidget*>(ce->child())->setVisible(d->isExpanded);
            }
            break;
        }
        case QEvent::LayoutRequest:
            if (d->animation->state() == QTimeLine::NotRunning) {
                setFixedHeight(sizeHint().height());
            }
            break;
        default:
            break;
    }

    return QWidget::event(event);
}

void KCollapsibleGroupBox::mousePressEvent(QMouseEvent *event)
{
    const QRect headerRect(0, 0, width(), d->headerSize.height());
    if (headerRect.contains(event->pos())) {
        toggle();
    }
    event->setAccepted(true);
}

//if mouse has changed whether it is in the top bar or not refresh to change arrow icon
void KCollapsibleGroupBox::mouseMoveEvent(QMouseEvent *event)
{
    const QRect headerRect(0, 0, width(), d->headerSize.height());
    bool headerContainsMouse = headerRect.contains(event->pos());

    if (headerContainsMouse != d->headerContainsMouse) {
        d->headerContainsMouse = headerContainsMouse;
        update();
    }

    QWidget::mouseMoveEvent(event);
}

void KCollapsibleGroupBox::leaveEvent(QEvent *event)
{
    d->headerContainsMouse = false;
    update();
    QWidget::leaveEvent(event);
}

void KCollapsibleGroupBox::keyPressEvent(QKeyEvent *event)
{
    //event might have just propogated up from a child, if so we don't want to react to it
    if (!hasFocus()) {
        return;
    }
    const int key = event->key();
    if (key == Qt::Key_Space || key == Qt::Key_Enter || key == Qt::Key_Return) {
        toggle();
        event->setAccepted(true);
    }
}

void KCollapsibleGroupBox::resizeEvent(QResizeEvent *event)
{
    int top, left, right, bottom;
    getContentsMargins(&left, &top, &right, &bottom);

    if (layout()) {
        //we don't want the layout trying to fit the current frame of the animation so always set it to the target height
        layout()->setGeometry(QRect(left, top, width() - left - right, layout()->sizeHint().height()));
    }

    Q_UNUSED(bottom)
    QWidget::resizeEvent(event);
}

void KCollapsibleGroupBoxPrivate::recalculateHeaderSize()
{
    QStyleOption option;
    option.initFrom(q);

    QSize textSize = q->style()->itemTextRect(option.fontMetrics, QRect(), Qt::TextShowMnemonic, false,
                                     title).size();

    headerSize = q->style()->sizeFromContents(QStyle::CT_CheckBox, &option, textSize, q);
    q->setContentsMargins(q->style()->pixelMetric(QStyle::PM_IndicatorWidth), headerSize.height(), 0, 0);
}

void KCollapsibleGroupBoxPrivate::updateChildrenVisibility(bool visible)
{
    foreach (QObject *child, q->children()) {
        QWidget *widget = qobject_cast<QWidget*>(child);
        if (widget) {
            widget->setVisible(visible);
        }
    }
}

QSize KCollapsibleGroupBoxPrivate::contentSize() const
{
    if (q->layout()) {
        const QMargins margins = q->contentsMargins();
        const QSize marginSize(margins.left() + margins.right(), margins.top() + margins.bottom());
        return q->layout()->sizeHint() + marginSize;
    }
    return QSize(0,0);
}

QSize KCollapsibleGroupBoxPrivate::contentMinimumSize() const
{
    if (q->layout()) {
        const QMargins margins = q->contentsMargins();
        const QSize marginSize(margins.left() + margins.right(), margins.top() + margins.bottom());
        return q->layout()->minimumSize() + marginSize;
    }
    return QSize(0,0);
}


#include "kcollapsiblegroupbox.moc"