basetreeview.cpp 11.1 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13
14
** conditions see http://www.qt.io/licensing.  For further information
** use the contact form at http://www.qt.io/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18
19
20
21
22
23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
25
26
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
27
28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30
31
32

#include "basetreeview.h"

33
34
#include <utils/qtcassert.h>

35
36
#include <QDebug>
#include <QFontMetrics>
37
#include <QHeaderView>
38
39
#include <QItemDelegate>
#include <QLabel>
40
#include <QMap>
41
42
#include <QMenu>
#include <QMouseEvent>
43
#include <QSettings>
hjk's avatar
hjk committed
44
#include <QTimer>
45
46

namespace Utils {
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
namespace Internal {

const char ColumnKey[] = "Columns";

class BaseTreeViewPrivate : public QObject
{
    Q_OBJECT

public:
    explicit BaseTreeViewPrivate(BaseTreeView *parent)
        : q(parent), m_settings(0), m_expectUserChanges(false)
    {}

    bool eventFilter(QObject *, QEvent *event)
    {
        if (event->type() == QEvent::MouseMove) {
            // At this time we don't know which section will get which size.
            // But we know that a resizedSection() will be emitted later.
            QMouseEvent *me = static_cast<QMouseEvent *>(event);
            if (me->buttons() & Qt::LeftButton)
                m_expectUserChanges = true;
        }
        return false;
    }

    void readSettings()
    {
        // This only reads setting, does not restore state.
        // Storage format is a flat list of column numbers and width.
        // Columns not mentioned are resized to content////
        m_userHandled.clear();
        if (m_settings && !m_settingsKey.isEmpty()) {
            m_settings->beginGroup(m_settingsKey);
            QVariantList l = m_settings->value(QLatin1String(ColumnKey)).toList();
            QTC_ASSERT(l.size() % 2 == 0, qDebug() << m_settingsKey; l.append(0));
            for (int i = 0; i < l.size(); i += 2) {
                int column = l.at(i).toInt();
                int width = l.at(i + 1).toInt();
                QTC_ASSERT(column >= 0 && column < 20, qDebug() << m_settingsKey << column; continue);
                QTC_ASSERT(width > 0 && width < 10000, qDebug() << m_settingsKey << width; continue);
                m_userHandled[column] = width;
            }
            m_settings->endGroup();
        }
    }

    void restoreState()
    {
        if (m_settings && !m_settingsKey.isEmpty()) {
            QHeaderView *h = q->header();
            for (auto it = m_userHandled.constBegin(), et = m_userHandled.constEnd(); it != et; ++it) {
                const int column = it.key();
                const int targetSize = it.value();
                const int currentSize = h->sectionSize(column);
                if (targetSize > 0 && targetSize != currentSize)
                    h->resizeSection(column, targetSize);
            }
        }
    }

    void saveState()
    {
        if (m_settings && !m_settingsKey.isEmpty()) {
            m_settings->beginGroup(m_settingsKey);
            QVariantList l;
            for (auto it = m_userHandled.constBegin(), et = m_userHandled.constEnd(); it != et; ++it) {
                const int column = it.key();
                const int width = it.value();
                QTC_ASSERT(column >= 0 && column < q->model()->columnCount(), continue);
                QTC_ASSERT(width > 0 && width < 10000, continue);
                l.append(column);
                l.append(width);
            }
            m_settings->setValue(QLatin1String(ColumnKey), l);
            m_settings->endGroup();
        }
    }

    Q_SLOT void handleSectionResized(int logicalIndex, int /*oldSize*/, int newSize)
    {
        if (m_expectUserChanges) {
            m_userHandled[logicalIndex] = newSize;
            saveState();
            m_expectUserChanges = false;
        }
    }

    int suggestedColumnSize(int column) const
    {
        QHeaderView *h = q->header();
        QTC_ASSERT(h, return -1);
        QAbstractItemModel *m = q->model();
        QTC_ASSERT(m, return -1);

        QModelIndex a = q->indexAt(QPoint(1, 1));
        a = a.sibling(a.row(), column);
        QFontMetrics fm = q->fontMetrics();
        int minimum = fm.width(m->headerData(column, Qt::Horizontal).toString());
        const int ind = q->indentation();
        for (int i = 0; i < 100 && a.isValid(); ++i) {
            const QString s = m->data(a).toString();
            int w = fm.width(s) + 10;
            if (column == 0) {
                for (QModelIndex b = a.parent(); b.isValid(); b = b.parent())
                    w += ind;
            }
            if (w > minimum)
                minimum = w;
            a = q->indexBelow(a);
        }
        return minimum;
    }

    Q_SLOT void resizeColumns()
    {
        QHeaderView *h = q->header();
        QTC_ASSERT(h, return);

        if (m_settings && !m_settingsKey.isEmpty()) {
            for (int i = 0, n = h->count(); i != n; ++i) {
                int targetSize;
                if (m_userHandled.contains(i))
                    targetSize = m_userHandled.value(i);
                else
                    targetSize = suggestedColumnSize(i);
                const int currentSize = h->sectionSize(i);
                if (targetSize > 0 && targetSize != currentSize)
                    h->resizeSection(i, targetSize);
            }
        }
    }

    Q_SLOT void rowActivatedHelper(const QModelIndex &index)
    {
        q->rowActivated(index);
    }

    Q_SLOT void rowClickedHelper(const QModelIndex &index)
    {
        q->rowClicked(index);
    }

    Q_SLOT void toggleColumnWidth(int logicalIndex)
    {
        QHeaderView *h = q->header();
        const int currentSize = h->sectionSize(logicalIndex);
        const int suggestedSize = suggestedColumnSize(logicalIndex);
        int targetSize = suggestedSize;
        // We switch to the size suggested by the contents, except
        // when we have that size already, in that case minimize.
        if (currentSize == suggestedSize) {
            QFontMetrics fm = q->fontMetrics();
            int headerSize = fm.width(q->model()->headerData(logicalIndex, Qt::Horizontal).toString());
            int minSize = 10 * fm.width(QLatin1Char('x'));
            targetSize = qMax(minSize, headerSize);
        }
        h->resizeSection(logicalIndex, targetSize);
        m_userHandled.remove(logicalIndex); // Reset.
        saveState();
    }

public:
    BaseTreeView *q;
    QMap<int, int> m_userHandled; // column -> width, "not present" means "automatic"
    QSettings *m_settings;
    QString m_settingsKey;
    bool m_expectUserChanges;
};
215

216
217
218
class BaseTreeViewDelegate : public QItemDelegate
{
public:
219
    BaseTreeViewDelegate(QObject *parent): QItemDelegate(parent) {}
220
221
222
223
224
225
226
227
228
229
230
231
232
233

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const
    {
        Q_UNUSED(option);
        QLabel *label = new QLabel(parent);
        label->setAutoFillBackground(true);
        label->setTextInteractionFlags(Qt::TextSelectableByMouse
            | Qt::LinksAccessibleByMouse);
        label->setText(index.data().toString());
        return label;
    }
};

234
235
236
237
} // namespace Internal

using namespace Internal;

238
BaseTreeView::BaseTreeView(QWidget *parent)
239
    : TreeView(parent), d(new BaseTreeViewPrivate(this))
240
241
242
243
244
245
246
{
    setAttribute(Qt::WA_MacShowFocusRect, false);
    setFrameStyle(QFrame::NoFrame);
    setRootIsDecorated(false);
    setIconSize(QSize(10, 10));
    setSelectionMode(QAbstractItemView::ExtendedSelection);
    setUniformRowHeights(true);
247
    setItemDelegate(new BaseTreeViewDelegate(this));
248
249
250

    QHeaderView *h = header();
    h->setDefaultAlignment(Qt::AlignLeft);
251
    h->setSectionsClickable(true);
252
    h->viewport()->installEventFilter(d);
253
254

    connect(this, SIGNAL(activated(QModelIndex)),
255
        d, SLOT(rowActivatedHelper(QModelIndex)));
256
    connect(this, SIGNAL(clicked(QModelIndex)),
257
258
259
260
261
262
263
264
265
266
        d, SLOT(rowClickedHelper(QModelIndex)));
    connect(h, SIGNAL(sectionClicked(int)),
        d, SLOT(toggleColumnWidth(int)));
    connect(h, SIGNAL(sectionResized(int,int,int)),
        d, SLOT(handleSectionResized(int,int,int)));
}

BaseTreeView::~BaseTreeView()
{
    delete d;
267
268
}

269
void BaseTreeView::setModel(QAbstractItemModel *m)
270
{
271
272
273
274
275
276
277
278
279
280
281
282
283
    struct ExtraConnection {
        const char *signature;
        const char *qsignal;
        QObject *receiver;
        const char *qslot;
    };
#define DESC(sign, receiver, slot) { #sign, SIGNAL(sig), receiver, SLOT(slot) }
    const ExtraConnection c[] = {
        DESC(columnAdjustmentRequested(), d, resizeColumns()),
        DESC(requestExpansion(QModelIndex), this, expand(QModelIndex))
    };
#undef DESC

284
285
    QAbstractItemModel *oldModel = model();
    if (oldModel) {
286
287
288
289
290
        for (unsigned i = 0; i < sizeof(c) / sizeof(c[0]); ++i) {
            int index = model()->metaObject()->indexOfSignal(c[i].signature);
            if (index != -1)
                disconnect(model(), c[i].qsignal, c[i].receiver, c[i].qslot);
        }
291
    }
292

293
    TreeView::setModel(m);
294

295
    if (m) {
296
297
298
299
300
        for (unsigned i = 0; i < sizeof(c) / sizeof(c[0]); ++i) {
            int index = m->metaObject()->indexOfSignal(c[i].signature);
            if (index != -1)
                connect(model(), c[i].qsignal, c[i].receiver, c[i].qslot);
        }
301
        d->restoreState();
hjk's avatar
hjk committed
302
    }
303
304
305
306
}

void BaseTreeView::mousePressEvent(QMouseEvent *ev)
{
307
    TreeView::mousePressEvent(ev);
308
309
    const QModelIndex mi = indexAt(ev->pos());
    if (!mi.isValid())
310
        d->toggleColumnWidth(columnAt(ev->x()));
311
312
}

313
void BaseTreeView::setSettings(QSettings *settings, const QByteArray &key)
314
{
315
316
317
318
    QTC_ASSERT(!d->m_settings, qDebug() << "DUPLICATED setSettings" << key);
    d->m_settings = settings;
    d->m_settingsKey = QString::fromLatin1(key);
    d->readSettings();
319
320
}

321
322
323
324
325
326
327
328
329
330
331
332
QModelIndexList BaseTreeView::activeRows() const
{
    QItemSelectionModel *selection = selectionModel();
    QModelIndexList indices = selection->selectedRows();
    if (indices.isEmpty()) {
        QModelIndex current = selection->currentIndex();
        if (current.isValid())
            indices.append(current);
    }
    return indices;
}

333
} // namespace Utils
334
335

#include "basetreeview.moc"