[Qt-interest] GUI, Qt, Sorting, QTableWidget, NO sorting even after setSortingEnabled()
Irfan Omair
irfan.omair.qt at gmail.com
Wed Aug 4 20:49:55 CEST 2010
I dont see any other direct way of doing that other than
reimplementing operator< in the subclass.
By the way only few lines of code will do the trick.
bool myListItem ::operator< ( const QTableWidgetItem &other ) const
{
if( this->text().toInt() < other.text().toInt() )
return true;
else
return false;
}
See detail example below.
#include <QtGui>
class myListItem: public QObject, public QTableWidgetItem
{
Q_OBJECT
public:
bool myListItem ::operator< ( const QTableWidgetItem &other ) const
{
if( this->text().toInt() < other.text().toInt() )
return true;
else
return false;
}
};
class MainWindow : public QMainWindow
{
public:
MainWindow(QWidget *parent = 0)
: QMainWindow(parent)
{
QWidget *w = new QWidget;
setCentralWidget(w);
QVBoxLayout *layout = new QVBoxLayout(w);
QTableWidget *list = new QTableWidget(2,1);
myListItem *item = new myListItem;
item->setText(QString("%1").arg(10));
list->setItem(0,0,item);
item = new myListItem;
item->setText(QString("%1").arg(15));
list->setItem(1,0,item);
list->setSortingEnabled(true);
layout->addWidget(list);
}
};
#include "main.moc"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
Hope this helps
Regards,
Irfan Omair
Qt Developer
On Wed, Aug 4, 2010 at 11:19 AM, Mandaya Prakash
<mandaya.prakash at gmail.com>wrote:
>
> Hi All,
>
> My company has now started usin Qt and I am having some probelm with
> QTableWidget sorting.
>
> I have a QTableWidget. And I fill it with some QTableWidgetItem, initiated
> by simple QString,
> actually, just a number like 1,2,10, etc. The problem is that when I set
> tableWidget->setSortingEnabled(true); and then sort by this column, the
> order is 1,10,2..., looks like it's compared as string.
> I don't want to change the code a lot (e.g., creating a customized
> sub-class) to make it sort correctly. So is there any option of the
> table/item that I can just set to make it work?
> Thank you in advance
>
> BR
>
> Prakash.
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20100804/cebfd1fc/attachment.html
More information about the Qt-interest-old
mailing list