PDA

View Full Version : sortItems by double value in QTableWidget



wconstan
26th December 2009, 20:03
I have the following code for formatting a QTableWidget. The sortItems method sorts alphabetically and not numerically. Is there an easy fix to this code to be able to do so? Please be explicit as I a quite new at Qt.


void myClass::formatTable(QTableWidget *table, double minimum, double maximum)
{
double val;
int i;
int nrow = table->rowCount();
QTableWidgetItem *item;
table->setSortingEnabled(false);

for (i = 0; i < nrow; i++)
{
// obtain tableWidgetItem
item = table->item(i, 0);

// ensure item is not NULL, otherwise the application will crash!
if (!item)
{
continue;
}

// obtain cell string and convert to double value
val = item->text().toDouble();

// make sure entries like ".7" are converted to "0.7". otherwise, sorting will be incorrect
item->setText(QString::number(val));

// TRIED THIS BUT DID NOT WORK
// item->setData(Qt::DisplayRole, val);


// check the low bound
if (val <= minimum)
{
item->setText(QString::number(minimum));
}

// check the high bound
if (val >= maximum)
{
item->setText(QString::number(maximum));
}

// justification
item->setTextAlignment(Qt::AlignRight);
}

table->sortItems(0, Qt::AscendingOrder);
}

Lykurg
26th December 2009, 20:07
use QTableWidgetItem::setData() when filling your table. Then all will work out of the box.

Nothing
27th December 2009, 07:45
item->setData(Qt::DisplayRole, val); = item->setText(QString::number(val));
:)

Lykurg
27th December 2009, 09:13
item->setData(Qt::DisplayRole, val); = item->setText(QString::number(val));
:)
First please use the CODE tags or at least turn off the smilies. Then you probably intend to use == instead of = but apart from that both expressions are not the same! In both cases the same is shown but when it comes to sorting the table the former is sorted numerical and the later alphabetical.

wconstan
27th December 2009, 18:20
Thanks much Lykurg for your reply. That worked like a charm.