aboutsummaryrefslogtreecommitdiffstats
path: root/examples/quickcontrols/filesystemexplorer/linenumbermodel.cpp
blob: 5a7982dca93d3bf8e9ee114ae2e8d38e5d306661 (plain)
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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "linenumbermodel.h"

#include <QQmlInfo>

/*!
    When using an integer model based on the line count of the editor,
    any changes in that line count cause all delegates to be destroyed
    and recreated. That's inefficient, so instead, we add/remove model
    items as necessary ourselves, based on the lineCount property.
*/
LineNumberModel::LineNumberModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

int LineNumberModel::lineCount() const
{
    return m_lineCount;
}

void LineNumberModel::setLineCount(int lineCount)
{
    if (lineCount < 0) {
        qmlWarning(this) << "lineCount must be greater than zero";
        return;
    }

    if (m_lineCount == lineCount)
        return;

    if (m_lineCount < lineCount) {
        beginInsertRows(QModelIndex(), m_lineCount, lineCount - 1);
        m_lineCount = lineCount;
        endInsertRows();
    } else if (m_lineCount > lineCount) {
        beginRemoveRows(QModelIndex(), lineCount, m_lineCount - 1);
        m_lineCount = lineCount;
        endRemoveRows();
    }

    emit lineCountChanged();
}

int LineNumberModel::rowCount(const QModelIndex &) const
{
    return m_lineCount;
}

QVariant LineNumberModel::data(const QModelIndex &index, int role) const
{
    if (!checkIndex(index) || role != Qt::DisplayRole)
        return QVariant();

    return index.row();
}