QTreeView insertRows通过方法挤压/直接调用工作

QTreeView insertRows via method crushs / direct call works

本文关键字:调用 工作 insertRows 方法 QTreeView      更新时间:2023-10-16

我有以下奇怪的问题

我已经实现了一个QAbstractItemModel,我可以插入子节点到树视图,但当我试图通过insertRows()方法添加节点时,会发生一些奇怪的事情。

首先调用all:

QApplication a(argc, argv);
QResource::registerResource("Qt5Tutorial.rcc");
QTreeView *treeView = new QTreeView();
treeView->show();
Node rootNode("rootNode");
CameraNode childNode0("childNode0", &rootNode);
CameraNode childNode1("childNode1", &rootNode);
LightNode childNode2("childNode2", &rootNode);
CameraNode childNode3("childNode3", &childNode0);
TransformNode childNode4("childNode4", &childNode2);
TransformNode tryNode("potato");
// setup model
ObjectTreeModel model(&rootNode);
treeView->setModel(&model);
// insert directly via the insert child method 
// this works!
childNode0.insertChild(1, &tryNode);
// get the QModelIndex of childNode1
// must be passed in the insertRows() method 
QModelIndex index(model.index(1, 0, QModelIndex()));
// the output is "childNode1" what is totally right
qDebug() << "index: "<<static_cast<Node*>(index.internalPointer())->getName();
// output see posted beneath
qDebug() << rootNode.log();
// should insert in "childNode1" -> at 0th position and just 1 Node object
// see the method beneath
model.insertRows(0, 1, index);
// if i try to call the method rootNode.log(); now again, it crashes 
return a.exec();

这是rootNode.log()调用的输出:

---rootNode
    ---childNode0
            ---childNode3
            ---potato
    ---childNode1
    ---childNode2
            ---childNode4

可以看到,"Potato"节点被正确插入。

查看图片http://www10.pic-upload.de/04.01.13/m65huuqq4ruu.png

但是一旦我尝试扩展childNode1节点,它就崩溃了。但是看看上面代码中的最后一条注释。正如我所提到的->如果我现在尝试输出树视图(它遍历所有节点),它会崩溃。

当方法被调用时,一切似乎都很好-就在我试图展开树视图时,它崩溃了->调试输出让我认为一切都应该是好的

实际的错误消息是读取位置…时的访问冲突。(翻译自德语-不知道在英语中是否叫相同)

 bool ObjectTreeModel::insertRows(int position, int row, const QModelIndex &parent)
{
beginInsertRows(parent, position, position + row - 1);
Node *parentNode = getNode(parent);
qDebug() << "parentName: " << parentNode->getName();
bool success = false;
for(int i = position; i < row; i++)
{
    qDebug() << "inside loop"; 
    qDebug() << "position: " << position << "row: " << row;
    TransformNode childNode("insertedNode");
    success = parentNode->insertChild(i, &childNode);
    qDebug() << "success: " << success;
}
endInsertRows();
return success;

}

上述方法的调试输出:

getNode: successful 
parentName: "childNode1" 
inside loop 
position:  0 row:  1 
called inserchild 
success:  true 

我不知道为什么会发生这种情况,因为调试输出似乎是正确的,它应该基本上与通过insertChild方法直接插入节点相同。

我希望有人知道为什么它不起作用。

致以最诚挚的问候,Michael

几乎一切都是正确的。只有这两行不行:

TransformNode *childNode = new TransformNode("insertedNode");
success = parentNode->insertChild(i, childNode);
相关文章: