Tables and trees are not isomorphic, that is the problem.
A tree holds what are essentially tables (their elements are indexed by [row,column]) in some sort of
hierarchy. If you collapse a tree, you end up with a table.
In order to impose such a hierarchy on a table, the table / table elements need to store their
row/column data as usual plus references to their parents. Then when you rebuild the tree check this
reference to find out which node to attach the table element to.
Alternatively for example in cases like yours where there is a defined structure, the parent reference
is not needed because it can be calculated by the model being used:
#include <QtGui>
int main(int argc, char **argv) {
int maxrows = 4;
int maxcols = 4;
for (int row = 0; row < maxrows; ++row) {
for (int column = 0; column < maxcols; ++column) {
tableModel.setItem(row, column, item);
}
}
tablev.setModel(&tableModel);
tablev.show();
for (int row = 0; row < maxrows; ++row) {
for (int col = 0; col < maxcols; ++col) {
// grab the data out of the table
parentItem->appendRow(item);
parentItem = item;
}
parentItem = treeModel.invisibleRootItem();
}
treev.setModel(&treeModel);
treev.show();
return app.exec();
}
#include <QtGui>
int main(int argc, char **argv) {
QApplication app(argc, argv);
int maxrows = 4;
int maxcols = 4;
QStandardItemModel tableModel(maxrows, maxcols);
for (int row = 0; row < maxrows; ++row) {
for (int column = 0; column < maxcols; ++column) {
QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
tableModel.setItem(row, column, item);
}
}
QTableView tablev;
tablev.setModel(&tableModel);
tablev.show();
QStandardItemModel treeModel;
QStandardItem *parentItem = treeModel.invisibleRootItem();
for (int row = 0; row < maxrows; ++row) {
for (int col = 0; col < maxcols; ++col) {
// grab the data out of the table
QStandardItem *item = new QStandardItem(tableModel.data(tableModel.index(row, col, QModelIndex()), Qt::DisplayRole).toString());
parentItem->appendRow(item);
parentItem = item;
}
parentItem = treeModel.invisibleRootItem();
}
QTreeView treev;
treev.setModel(&treeModel);
treev.show();
return app.exec();
}
To copy to clipboard, switch view to plain text mode
The problem here is that after creation, the tree and table are independant of each other.
I suppose that they could be kept in sync by implementing their respective data changed signals/slots.
Bookmarks