File: samplemodel.cpp

package info (click to toggle)
cppcheck 2.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,132 kB
  • sloc: cpp: 268,935; python: 20,890; ansic: 8,090; sh: 1,045; makefile: 1,008; xml: 1,005; cs: 291
file content (66 lines) | stat: -rw-r--r-- 1,444 bytes parent folder | download | duplicates (2)
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
#include "samplemodel.h"

#include <QDebug>
#include <QRandomGenerator>

SampleModel::SampleModel(QObject *parent) : QAbstractListModel(parent)
{}

int SampleModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent)
    return _data.size();
}

QVariant SampleModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.row() < 0 || index.row() > _data.count() - 1)
        return QVariant();

    auto row = _data.at(index.row());

    switch (role) {
    case IdRole:
        return index.row();

    case NameRole:
        return row.first;

    case GradeRole:
        return row.second;
    }

    return QVariant();
}

QHash<int, QByteArray> SampleModel::roleNames() const
{
    return {
        {IdRole, "id"},
        {NameRole, "name"},
        {GradeRole, "grade"}
    };
}

void SampleModel::fillSampleData(int size)
{
    QString abs = "qwertyuiopasdfghjklzxcvbnm";
    QRandomGenerator r;
    for (auto i = 0; i < size; i++) {
        Row row;
        auto nameLen = r.bounded(3, 8);
        QString name;
        for (int c = 0; c < nameLen; ++c)
            name.append(abs.at(r.bounded(0, abs.size() - 1)));

        row.first = name;
        row.second = r.bounded(0, 20);
        _data.append(row);
    }

    qDebug() << _data.size() << "item(s) added as sample data";
    beginInsertRows(QModelIndex(), 0, _data.size() - 1);
    endInsertRows();
}