View Full Version : QTableWidget sorting
abrou
28th January 2008, 19:20
Hello, I am making a QTableWidget which is working nicely. I want the user to be able to sort each column, which is also working, but I don't like how it sorts columns with numbers. It will sort the numbers from 0 to 10 like this:
0
1
10
2
3
4
5
6
7
8
9
But I want it like this:
0
1
2
3
4
5
6
7
8
9
10
enum Qt::SortOrder just seems to have AscendingOrder and DescendingOrder. Is there anyway to achieve what I want?
Thanks!
jpn
28th January 2008, 19:41
Set the data as numbers instead of as text:
int i = 0;
QTableWidgetItem* item = ...
//item->setText(QString::number(i)); // <-- no
item->setData(Qt::DisplayRole, i); // <-- yes
zeFree
6th June 2012, 10:53
I was facing a similar problem, just a bit more complex than this one.
In a QTableWidget, in some columns I had simple numeric values and in others I wanted to show them with a " %" appended.
e.g. "65.32" -----> "65.32 %"
But when sorting I wanted the cells to be sorted numerically.
Thus I subclassed the QTableWidgetItem and then implemented the "<" operator to sort numbers and not strings.
class MyTableWidgetItem : public QTableWidgetItem
{
if(text().contains("%"))
{
QString str1 = text();
str1.chop(2);
QString str2 = other.text();
str2.chop(2);
return str1.toDouble() < str2.toDouble();
}
else
{
return text().toDouble() < other.text().toDouble();
}
}
Then while populating the table I passed instances of my custom items instead of the generic ones.
I learnt the basics for this technique from here (http://stackoverflow.com/questions/7848683/how-to-sort-datas-in-qtablewidget).
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.