0
votes

I'm using QTreeWidget:

mTreeWdg->setSelectionMode( QAbstractItemView::ExtendedSelection );

mTreeWdg->setSelectionBehavior(QAbstractItemView::SelectRows);

and have a function to delete all selected items in the tree. When I click on each one, it works fine. But when i select items by clicking on first, end then the last item, it deletes the first and then crashes.

OnBtnClickedDelete(){
QList<QTreeWidgetItem* > list = mTree->selectedItems();
QList<QTreeWidgetItem*>::iterator it;

for(it=list.begin(); it!= list.end(); it++)
{
try
{  
    QTreeWidgetItem* current_item=*it;
    if(current_item != 0 )
    {
        int ind=current_item->data(0,Qt::UserRole).toInt();
        if(ind > 0)
        {
            if(MyMessageBox(
                tr("Are you sure you want to " \
                "delete this ?"),       
                QMessageBox::Question,
                QMessageBox::Yes | QMessageBox::No)==QMessageBox::Yes)
            {
                mPro.mDelete(ind-1);
                mSth.Clear();

                this->RefreshTree();

                EnableAllControls(false);

                if(this->mTree->topLevelItemCount() == 1 )
                {             
                    EnableButtons(FALSE);
                    set_enabled(mButtonGenerate,true);
                    set_enabled(mButtonNew,true);
                }
            }
        }            
    }    
}

catch (std::exception& e)
{
    default_exception_handler(e);
}
}}}
1
what is mPro? and mSth? of course if you change QTreeWidget hierarchy ( this->RefreshTree( ) ), current iterators become invalid... maybe you need a "break"eferion
But why this works when i click multiple items with mouse ? If i click 3 different items, it deletes all of themuser2944505
Try to put RefreshTree and following lines out of the loop. Don't refresh the tree widget while you are iterating. If you dont wanna refresh tree without deletions, use bool variable.eferion

1 Answers

0
votes

Just use this, i assume you have selected some items then click a delete button, just make the button call this line of code

qDeleteAll(this->mTree->selectedItems());