2

I have a QTableWidget and I want to sort the components of this table according to the values of the zero column, I used this code :

ui->tableParticle->sortByColumn(0,Qt::AscendingOrder);

but it gives no good results, the image below shows you the problem I sought solution but found nothing, sorry I can't put all the code because it's very long. Image

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
all.west
  • 71
  • 1
  • 1
  • 11
  • I also used : ui->tableParticle->sortItems(0,Qt::AscendingOrder); and it does not work . – all.west Jun 19 '16 at 14:12
  • "* I can't put all the code because it's very long*" is exactly the reason you're encouraged to create a [mcve] of your problem. I'd expect it to be around 10-20 lines. – Toby Speight Nov 06 '17 at 17:21

3 Answers3

3

By deafault QTableWidget sorts columns as ordinary strings. If you search for questions like "custom sorting in QTableWidget", you will find solutions to your answer, e.g.

  1. Custom sorting method of QTableView?

  2. Custom Sorting in QTableWidget

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Seleznev Anton
  • 641
  • 5
  • 14
  • My table widget inherits from QStyledItemDelegate not QTableWidget, also i see the answers and i dont understand very well because im new in Qt and C++, I see that i should reimplement operator<(), but i dont understand how to subclass the QTableWidgetItem, i need to create a new class or change my class who creates the table ? – all.west Jun 19 '16 at 15:09
  • I add that to my code but it dosn't work :
    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()); } };
    – all.west Jun 19 '16 at 17:00
2

I find also this answer add by SoloPilot, but i dont know how the pad the number strings with blanks and when I will add the line (' '+numStr)[-4:] :

The answer

One way that worked in my situation was

  1. before filling the table, turn off sorting:

table.setSortingEnabled(False)

  1. pad the number strings with blanks and make all strings in the column have the same length:

('    '+numStr)[-4:]

  1. after filling the table, turn on sorting:

table.setSortingEnabled(True)

This fixed the row sorting problem and the numerical order.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
all.west
  • 71
  • 1
  • 1
  • 11
-1

I add that before setItem and it's work :

ui->table->horizontalHeader()->sortIndicatorOrder();
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
all.west
  • 71
  • 1
  • 1
  • 11