sortItems by double value in QTableWidget
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.
Code:
void myClass
::formatTable(QTableWidget *table,
double minimum,
double maximum
) {
double val;
int i;
int nrow = table->rowCount();
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);
}
Re: sortItems by double value in QTableWidget
use QTableWidgetItem::setData() when filling your table. Then all will work out of the box.
Re: sortItems by double value in QTableWidget
item->setData(Qt::DisplayRole, val); = item->setText(QString::number(val));
:)
Re: sortItems by double value in QTableWidget
Quote:
Originally Posted by
Nothing
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.
Re: sortItems by double value in QTableWidget
Thanks much Lykurg for your reply. That worked like a charm.