QAbstractTableModel column sum
-
Need some help figuring out how to do a simple addition calculation to a QAbstractTableModel. Let's say I have a simple flat table model with the following rows.
QString, int
Source1topicA , 3
Source1topicB , 1
Source1topicC , 2
Source2topicA , 3
Source2topicB , 1
Source2topicC , 2
Source3topicA , 3
Source3topicB , 1
Source3topicC , 2.. and I out like to view the table in a couple different ways:
first (which I have already figured out - using qsortfilterproxymodel)
Source1topicA , 3
Source1topicB , 1
Source1topicC , 2second (which is where I need a nudge). this would be a model that sorts each topic (which i understand would be done with a qsortfilterproxymodel) and calculates a sum.
topicA , 9
topicB , 3
topicC , 6reading around the forum, I am pretty sure this can be done by subclassing qabstractproxymodel, however, I when I started looking into subclassing I am not sure how the mapping would be done in mapTo/mapFromSource (since these are purely virtual functions and need to be re-implemented when subclassing). I already have a qsortfilterproxy model for doing the following:
Source1topicA , 3
Source2topicA , 3
Source3topicA , 3Thanks in advance,
goes2bob -
I believe I have solved my dilemma :)
I created a new qabstracttablemodel with a member variable as the custom qsortfilterproxymodel which collected all the topicA's from the source model . created a new QList <QPair<QString, int> >(to represent the columns i wished to display). re-implemented the rowCount() & columnCount() functions. then implemented the data() function as follows:
@QVariant AggregateModel::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
{
return QVariant();
}
if(index.row() >= entries.size() || index.row() < 0)
{
return QVariant();
}
if(role == Qt::DisplayRole)
{
QPair<QString, int>pair = entries.at(index.row());
if(index.column() == 0)
{
return pair.first;
}
else if(index.column() == 1)
{
int total = 0;
for(int i = 0; i < sortModel->rowCount(); ++i)
{
QModelIndex idx = sortModel->index(i, 1);
total += sortModel->data(idx).toInt();
}
return QVariant(total);
}
}
return QVariant();
}@The other important thing was to connect the dataChanged() signal from the sorted model to the dataChanged() signal in the AggregateModel:
@ bool connOk = connect(sortModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), aggModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)));
Q_ASSERT(connOk);
@Any comments, or possible improvements are welcome.