Custom Sorting in QTableWidget

妖精的绣舞 提交于 2019-12-14 02:17:38

问题


I have a QTableWidget and i am using its default sorting capability through header columns but one of my column in QTableWidget is integer type and through QTableWidget default sorting it is being sorted like a string.So there is any means by which i can use my own sorting functions for QTableWidget?


回答1:


You can try to subclass the QTableWidgetItem and reimplement operator<() of it. Than in your QTableWidget use this custom items instead of default QTableWidgetItems. Something like this:

class Item: public QTableWidgetItem
{

 public:
     [..]
     bool operator< (const QTableWidgetItem &other) const
     {
         // TODO: To be safe, check weather conversion to int is possible.
         return (this->text().toInt() < other.text().toInt());
     }
     [..]
 };

And in your table widget:

[..]
QTableWidgetItem *newItem = new Item("1");
tableWidget->setItem(row, column, newItem);
[..]



回答2:


I am not sure, but I don't think there is an easy way to change the sorting behaviour of a QTableWidget.

QTableWidget is just a convenience class for QTableView, which uses a default model. No guarantee, but what would try to do:

QTableWidget inheris the model() method from QTableView. With it you should be able to get the widget's model:

QAbstractItemModel *model = yourTableWidget->model();

This was the easy part. You now need a custom QSortFilterProxyModel, where you can override the virtual bool lessThan(const QModelIndex & left, const QModelIndex & right) const method.

And finally:

YourCustomFilterProxyModel *proxyModel = new YourCustomFilterProxyModel(this);
proxyModel->setSourceModel(model);
yourTableWidget->setModel(proxyModel);

No guarantee in so far that I never tried to replace the default model in a QTableWidget. If possible you should look into the Qt views and models. Initially they look harder to use, but it pays to get comfortable with them. IMHO QTableWidget is just an ancient relict from Qt3.




回答3:


Are you sure it didn't sort the data well? Make sure you do add number there, not string. So, to add 40 to QTableWidget row, you use this data:

36: {'firstname': 'b', 'lastname': '111', 'email': 'foo@gmail.com',
                     'affiliate': 'Stuart Little', 'total_account_value': 40},

Instead of this:

36: {'firstname': 'b', 'lastname': '111', 'email': 'foo@gmail.com',
                     'affiliate': 'Stuart Little', 'total_account_value': '40'},

QTableWidget will recognize it as integer and will sort it well



来源:https://stackoverflow.com/questions/18648215/custom-sorting-in-qtablewidget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!