Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Sorting in QTableWidget

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?

like image 873
kapil vermani Avatar asked Jun 06 '26 13:06

kapil vermani


1 Answers

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);
[..]
like image 135
vahancho Avatar answered Jun 10 '26 20:06

vahancho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!