Search code examples
c++qtqt4.8

ExtendedSelection with QTreeWidget crashes on Delete


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);
}
}}}

Solution

  • 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());