0

I often need to calculate the sum of all values in a table column so I can display various summaries, averages etc.

Right now I'm using my own helper method:

double Utils::columnSum(QAbstractTableModel *model, int columnIndex)
{
    Q_ASSERT_X(columnIndex >= 0 && columnIndex < model->columnCount(), "column sum", "column doesn't exist");
    double sum = 0;
    for (int ii = 0; ii < model->rowCount(); ++ii) {
        auto val = model->data(model->index(ii, columnIndex));
        bool ok;
        sum += val.toDouble(&ok);
        Q_ASSERT_X(val.isNull() || ok, "column sum", "column has non-numeric values");
    }
    return sum;
}

But if there is a framework provided function I'd rather use that, and knowing Qt, there probably is one somewhere but I couldn't find it.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • 1
    AFAIK there is not. But when you need that functionality multiple times you can try to write a custom proxy model, which does that for you. – Hayt Sep 08 '16 at 07:31
  • @Hayt Thanks for the suggestion, I might try it, although I don't have much experience with custom proxy models, I've never used them before. – sashoalm Sep 08 '16 at 07:40
  • It's not that hard. The Qt Documentation is pretty good there. The only thing you have to take care of is the re-mapping of the indexes but this is explained in the documentation. – Hayt Sep 08 '16 at 07:50

0 Answers0