PDA

View Full Version : QTableView insertRow 's dynamically



migel
30th June 2011, 10:59
I have periodically action to insert a single rows in existing QTableList.
Problem is that inserted row does not display items correctly in the right place.
I think it only happens when QtableList has set.


this->sortItems( 1, Qt::AscendingOrder );

When I remove sorting new rows appears on the bottom and all row items are displayed just find.

This is how I do it.


void ListView::insertRowFile(File *file) {
DEBUG;

int row = this->rowCount();
this->setRowCount(row+1);

QTableWidgetItem *dateItem = new QTableWidgetItem;
dateItem->setText(file->FileDate().toString("MM-dd-yyyy hh:mm"));
this->setItem(row, col, dateItem);

QTableWidgetItem *nameItem = new QTableWidgetItem;
nameItem->setIcon(file->FileIcon());
dateItem->setText(file->FileName());
this->setItem(row, col, nameItem);

}


I have tried also


this->insertRow(row);

instead of


this->setRowCount(row+1);

I set sortItems after displaying all rows in initial list construct.

What is a proper way to use insertRow with column sorting enabled ?

Thank You

Santosh Reddy
30th June 2011, 13:08
When inserting rows into QTableWidget, you need to disable sorting.

1. Disable Sorting
2. Insert Row(s), set all items in the row.
3. Enable Sorting

This is because, with sorting enabled, as soon as you insert a new item in a row, QTableWidget runs the sorting check on the new row item and relocates the item as per set sorting order, this means that the item row number is changed, and the row variable which you hold is no more valid:(, and when you to set the next item on the same row, it will give you spurious results, as the row variable is not valid any more

Other alternate to disable sorting, is to get the latest row number before setting the item, like this

1. Insert a new row (say row)
2. Set new item at row, at column 0
3. Get the new row number of the newly set item at column 0
4. Set next item at new row, at column 1
....next columns, as needed