PDA

View Full Version : Sort a Table that is not the root of the model



Poca
20th January 2015, 17:07
I have a custom QAbstractItemModel that is basically a tree of tables and i use a QTableView for each table to show every table.
when I try to sort a table by column using a standard QSortFilterProxyModel it only works for the first column.

I suspect it works that way because the sort is applied recursively but not for all the children of the root but only those in the corresponding column.

for exemple if i have the folowing model :

A
| 1 2 3
| 3 1 1
| 4 5 0
B
| a b c
| a e d
| f a a

I want to sort the table "A" by the third column to see in the A tableView :

4 5 0
3 1 1
1 2 3

I thought of using the QStandardItem::sortChildren method but it is not compatible with the use of a proxy model so i am stuck here with simple solutions.

If no such solution exist I will have to subclass QAbstractProxyModel but it seems rather non-trvial.

thanks for the help.

edit : here's a minmum example :


#include <QtWidgets>
#include <QStandardItemModel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStandardItemModel* model = new QStandardItemModel();

QStandardItem* Atable = new QStandardItem(3,3);
Atable->setData("A",Qt::EditRole);
Atable->setChild(0,0,new QStandardItem("1"));
Atable->setChild(0,1,new QStandardItem("2"));
Atable->setChild(0,2,new QStandardItem("3"));
Atable->setChild(1,0,new QStandardItem("3"));
Atable->setChild(1,1,new QStandardItem("2"));
Atable->setChild(1,2,new QStandardItem("1"));
Atable->setChild(2,0,new QStandardItem("2"));
Atable->setChild(2,1,new QStandardItem("1"));
Atable->setChild(2,2,new QStandardItem("3"));
model->appendRow(Atable);

QSortFilterProxyModel* proxy = new QSortFilterProxyModel();
proxy->setSourceModel(model);
QTableView* view = new QTableView();
view->setModel(proxy);
view->setRootIndex(proxy->mapFromSource(Atable->index()));
view->setSortingEnabled(true);
view->show();
return app.exec();
}

d_stranz
21st January 2015, 00:11
I think you need to re-read the docs for QStandardItemModel::appendRow():


When building a list or a tree that has only one column, this function provides a convenient way to append a single new item.

I don't think you are building the model you think you are.

Poca
21st January 2015, 09:22
When putting the entire model into a treeView the model looks like the one I thought I built.

I tried using setItem instead of appendRow.
It works but i need to increase the number of columns of the root item to be able to sort my table.

Thank you d_stranz for the help.