PDA

View Full Version : Trouble with sortItems coercion of text in QTableWidget



wconstan
18th November 2009, 04:45
I am using Qt Creator 1.2.92 based on Qt 4.6.0 32-bit.

I'd like to develop a private slot to check each item of a QTableWidget to ensure that the item is (1) a "number" and (2) that the number is on the range (0,1). In the case that either of these tests fail, I would like to set the item to some specified coerced value. The code I wrote to do so is as follows:


void myProject::formatTimingTable()
{
int i;
int j;
int nrow = ui->timing_tableWidget->rowCount();
int ncol = ui->timing_tableWidget->columnCount();
QString val;
QTableWidgetItem *item, *itemReplace;

for (i = 0; i < nrow; i++)
{
for (j = 0; j < ncol; j++)
{
item = ui->timing_tableWidget->item(i, j);

// ensure item is not NULL
if ( !item )
continue;

val = item->text();

if (val <= "0"){
itemReplace = new QTableWidgetItem("0.0001");
ui->timing_tableWidget->setItem(i, j, itemReplace);
}

if (val >= "1"){
itemReplace = new QTableWidgetItem("0.9999");
ui->timing_tableWidget->setItem(i, j, itemReplace);
}
}
}

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

This scheme works but the sortItems function can sometimes coerce a "0.0001" entry to "0". For example,



When I run the associated app and enter a "0" in the first row of the table I get the result as shown in the attached firstZeroEntry.jpg file. In this case, the scheme works as planned.

If, however, I then enter a "0" in the second row of the table I get the result shown in the attached secondZeroEntry.jpg file. In this case, the item in the first row is set to "0".

If I then enter "0.4" in the third row of the table, I get the result shown in the third attached thirdZeroEntry.jpg file. In this case, the first and second row contain the correct "0.0001" entry.


I have confirmed that the issue lies with sortItems function because when I comment the corresponding sort line in the code each "0" entry is suitably replaced by "0.0001" regardless of the the entry/row in the table.

While I'm not entirely enthused by this whole approach in general, I am a bit confused as to why sortItems is coercing entries as described. Am I missing something?

Secondly, is there an easier way to do all this? Suggestions/comments welcome.

Finally, I realize that ncol = 1 (always) in my case. I could adapt the code accordingly...but that is another issue.

Thanks!

Lykurg
18th November 2009, 08:38
if (val <= "0")

I would leave the quotation marks since you want compare the value numerical. Therefore also see toDouble().



itemReplace = new QTableWidgetItem("0.0001");
ui->timing_tableWidget->setItem(i, j, itemReplace);

There is no need to create a new item! just use your variable item and set the new text there.


See if that solves your problem.


EDIT: instead of test all the cells you could use QTableWidget::itemChanged() to only check a changed item.