Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a QTableView by a column?

Tags:

c++

qt

qtableview

I am using the QTableView to display a QAbstractTableModel:

#include <QtGui/QApplication>
#include <QAbstractTableModel>
#include <QTableView>

class TestModel : public QAbstractTableModel
{
public:
    int rowCount(const QModelIndex &parent = QModelIndex()) const
    {
        return 2;
    }
    int columnCount(const QModelIndex &parent = QModelIndex()) const
    {
        return 2;
    }
    QVariant data(const QModelIndex &index, int role) const
    {
        switch (role)
        {
        case Qt::DisplayRole:
        {
            return 4 - index.row() + index.column();
        }
        }
        return QVariant();
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QTableView table;
    TestModel model;
    table.setModel(&model);
    table.setSortingEnabled(true);
    table.sortByColumn(0, Qt::AscendingOrder);
    table.reset();
    table.show();

    return a.exec();
}

The displayed widget

The problem is that the result is exactly the same when I use:

table.sortByColumn(0, Qt::AscendingOrder);

or

table.sortByColumn(0, Qt::DescendingOrder);

or

table.sortByColumn(1, Qt::AscendingOrder);

or

table.sortByColumn(1, Qt::DescendingOrder);

What am I doing wrong?

like image 978
Martin Drozdik Avatar asked Jul 23 '12 03:07

Martin Drozdik


1 Answers

QAbstractTableModel provides an empty sort() implementation.

Try doing

TestModel model;
QSortFilterProxyModel proxyModel;
proxyModel.setSourceModel( &model );
table.setModel( &proxyModel ); 
like image 124
Tim Meyer Avatar answered Oct 01 '22 18:10

Tim Meyer