Moving selected items from QTableWidget1 to QTableWidget2
Hi community,
I need to move the selected items from 1 QTableWidget table to another QTableWidget table by pressing a button (both tables are in the same window).
The moving part is not the problem, the problem is removing the original rows.
Below my code:
Code:
void MainWindow::on_addReportButton_clicked()
{
// availableItemsTable is the source table
// selectedItemsTable is the destination table
QList<QTableWidgetItem*> items = ui->availableItemsTable->selectedItems();
if (items.isEmpty())
{
return;
}
for (auto &item : items)
{
auto selectedItem = ui->availableItemsTable->takeItem(item->row(), 0);
ui->selectedItemsTable->insertRow(ui->selectedItemsTable->rowCount());
ui->selectedItemsTable->setItem(ui->selectedItemsTable->rowCount() - 1, 0, selectedItem);
}
for (auto &item : items)
{
// Here I should remove the rows in the source table, but it removes wrong rows
ui->availableItemsTable->removeRow(item->row());
}
}
In the loop where I try to remove the rows in the source table, it removes wrong rows.
Any idea on what I am doing wrong?
Thanks in advance,
Franco
Re: Moving selected items from QTableWidget1 to QTableWidget2
Quote:
Any idea on what I am doing wrong?
Two things, probably:
1 - When you insert the item into table 2, it get a new row number that refers to its position in table 2, not the table it was removed from. The QTableWidgetItem instances are pointers, so their content can be changed by table 2 without the pointer itself changing.
2 - When you remove a row from table 1, all of the rows that come after that row get renumbered, so if you are removing rows from low to high row number, every row after the first one you remove will be wrong.
The trick to this is to make a list of the item row numbers -before- you do anything with the items. This list will refer to the row numbers in table 1 and won't be changed when you insert the items into table 2. Next step is to sort the list of row numbers in reverse (descending) order so when you remove rows, you start from the bottom of the table and work your way to the top. This way, none of the rows that come before the one you remove change row numbers.