Search code examples
qtqtreewidgetitem

QTreeWidgetItem reparenting


I'am trying to set new parent to QTreeWidgetItem, here is my code:

 1.if( it->parent() )//'it' is QTreeWidgetItem
 2.   {
 3.       QTreeWidgetItem* parent = it->parent();
 4.       parent->takeChild(parent->indexOfChild(it));
 5.   }
 7.   under->addChild( it );//'under' is new parent of 'it'

After the fourth line programm fails with read access violation at 0x0.

EDITED

    Q_CHECK_PTR(under);
    Q_CHECK_PTR(it);

    if( it->parent() )
    {
        QTreeWidgetItem* parent = it->parent();

        Q_CHECK_PTR(parent);

        Q_ASSERT( parent->child( parent->indexOfChild(it) ) == it );

        parent->removeChild(it);
        //or
        //it = new QTreeWidgetItem( *(parent->takeChild(parent->indexOfChild(it))) );
        //or
        //it = parent->takeChild(parent->indexOfChild(it));
        //or
        //parent->takeChild(parent->indexOfChild(it));
    }
    Q_CHECK_PTR(under);
    Q_CHECK_PTR(it);
    under->addChild( it );

Same result.


Solution

  • try this code:

    QTreeWidgetItem *parent = it->parent();
    parent->removeChild(it);
    under->addChild(it);  
    

    basically use removeChild insted of takeChild

    UPDATE
    removeChild Removes the given item from the parent and dosen't return anyting. note that the removed item will not be deleted. but takeChild returns the child pointer.