Download cpp source code

#include "GoldbachModel.h"
#include "GoldbachWorker.h"

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

int GoldbachModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return this->fetchedRowCount;
}

QVariant GoldbachModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() >= this->results.size() || index.row() < 0)
        return QVariant();

    if (role == Qt::DisplayRole)
        return this->results[ index.row() ];

    return QVariant();
}

void GoldbachModel::calculate(long long number)
{
    this->beginResetModel();

    if ( this->worker )
        this->worker->deleteLater();

    this->worker = new GoldbachWorker{number, this->results, this};

    this->connect( this->worker, &GoldbachWorker::progressUpdated, this, &GoldbachModel::updateProgress );
    this->connect( this->worker, &GoldbachWorker::calculationDone, this, &GoldbachModel::workerDone );

    this->worker->start();

    this->endResetModel();
}

void GoldbachModel::stop()
{
    Q_ASSERT(this->worker);
    this->worker->requestInterruption();
}

bool GoldbachModel::canFetchMore(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return this->fetchedRowCount < this->results.count();
}

void GoldbachModel::fetchMore(const QModelIndex &parent)
{
    Q_UNUSED(parent);

    int remainder = this->results.size() - this->fetchedRowCount;
    int itemsToFetch = qMin(100, remainder);

    if (itemsToFetch <= 0)
        return;

    beginInsertRows(QModelIndex(), this->fetchedRowCount, this->fetchedRowCount + itemsToFetch - 1);
    this->fetchedRowCount += itemsToFetch;
    endInsertRows();
}

void GoldbachModel::workerDone(long long sumCount)
{
    emit this->calculationDone(sumCount);
}

void GoldbachModel::updateProgress(int percent)
{
    emit this->progressUpdated(percent);

    if ( this->fetchedRowCount <= 0 )
        this->fetchMore(QModelIndex());
}