PDA

View Full Version : QTreeWidget loses selection while moving items down



kei
18th September 2009, 15:10
Hi,
i have a treewidget with items which i want to move up and down when pressing a key or button. The function "MoveUp" works fine but while using "MoveDown" it happens often (mostly after the first move downwards) that some of the selected items/rows (sometimes the first and last keep selected and sometimes one or two randomly) lose their selection.

Working moveUp():

void MainWindow::moveUp()
{
QList<QTreeWidgetItem *> selectedItems = ui->treeWidget->selectedItems();

if ( selectedItems.isEmpty())
return;

// If selection has the first line the items are on the top -> return
int row = ui->treeWidget->indexOfTopLevelItem( selectedItems.first() );
if ( row == 0 )
return;

QTreeWidgetItem *itemAbove;
QListIterator<QTreeWidgetItem *> it( selectedItems );

while ( it.hasNext() )
{
row = ui->treeWidget->indexOfTopLevelItem( it.next() );
itemAbove = ui->treeWidget->takeTopLevelItem( row - 1 );
ui->treeWidget->insertTopLevelItem( row, itemAbove );
}
}

Buggy(?) moveDown():

void MainWindow::moveDown()
{
QList<QTreeWidgetItem *> selectedItems = ui->treeWidget->selectedItems();

if ( selectedItems.isEmpty() )
return;

// If selection has the first line the items are on the top -> return
int row = ui->treeWidget->indexOfTopLevelItem( selectedItems.last() );
if ( row == ui->treeWidget->topLevelItemCount() - 1 )
return;

QTreeWidgetItem *itemBelow;
QListIterator<QTreeWidgetItem *> it( selectedItems );
it.toBack();

while ( it.hasPrevious() )
{
row = ui->treeWidget->indexOfTopLevelItem( it.previous() );
itemBelow = ui->treeWidget->takeTopLevelItem( row + 1 );
ui->treeWidget->insertTopLevelItem( row, itemBelow );
}
}

Edit: Not sure what's the problem but i solved it with the following better approach:

void MainWindow::moveDown()
{
QList<QTreeWidgetItem *> selectedItems = ui->treeWidget->selectedItems();

if ( selectedItems.isEmpty() )
return;

// If selection has the first line the items are on the top -> return
int row = ui->treeWidget->indexOfTopLevelItem( selectedItems.last() );
if ( row == ui->treeWidget->topLevelItemCount() - 1 )
return;

QTreeWidgetItem *itemBelow;

row = ui->treeWidget->indexOfTopLevelItem( selectedItems.last() );
itemBelow = ui->treeWidget->takeTopLevelItem( row + 1 );
ui->treeWidget->insertTopLevelItem( row + 1 - selectedItems.length() , itemBelow );

ui->treeWidget->scrollToItem( selectedItems.last() );
}

If somebody finds the error in the first version it would be nice to tell me.