C++ 如何按列对 QTableView 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11606259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:20:11 来源:igfitidea点击:
How to sort a QTableView by a column?
提问by Martin Drozdik
I am using the QTableView
to display a QAbstractTableModel:
我正在使用QTableView
来显示 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 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?
我究竟做错了什么?
回答by Tim Meyer
QAbstractTableModel
provides an empty sort()
implementation.
QAbstractTableModel
提供一个空的sort()
实现。
Try doing
尝试做
TestModel model;
QSortFilterProxyModel proxyModel;
proxyModel.setSourceModel( &model );
table.setModel( &proxyModel );