【问题标题】:QTreeWidgetItem reparentingQTreeWidgetItem 重设
【发布时间】:2015-11-03 12:02:13
【问题描述】:

我正在尝试将新父级设置为 QTreeWidgetItem,这是我的代码:

 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'

在第四行程序失败后,read access violation at 0x0.

已编辑

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

同样的结果。

【问题讨论】:

  • 像 GDB 这样的调试器会告诉你什么是空的,什么是失败的。
  • 没有什么是空的,这就是问题所在。在从父母那里带走或移除孩子之前,它、under 和 parent 都可以很好地工作。

标签: qt qtreewidgetitem


【解决方案1】:

试试这个代码:

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

基本上使用removeChild insted of takeChild

更新
removeChild 从父项中删除给定项目并且不返回任何内容。请注意,已删除的项目不会被删除。但takeChild 返回子指针。

【讨论】:

  • "parent" 是一个 QTreeWidget*(不是 QTreeWidgetItem*),但这不应该是这里的问题。如果您仍然对这几行有问题,我想错误出在其他地方,而不是您显示的内容。
  • “父”如何成为 QTreeWidget?根据 qt-help QTreeWidgetItem::parent() 返回 QTreeWidgetItem*。仅当 QTreeWidget 继承自 QTreeWidgetItem 时才会如此。
  • @A.Akzhigitov 你的第一个代码对我来说非常有效,我强烈怀疑问题出在你的初始化中。
  • 好的,我去看看。
  • @MesihAkbari 再问一个问题。除了return语句之外,takeChild和removeChild有什么区别吗?
猜你喜欢
  • 2018-10-29
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 2016-07-09
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
相关资源
最近更新 更多