C++ 添加到模型时Qt QTreeView未更新

C++ 添加到模型时Qt QTreeView未更新,c++,qt,C++,Qt,有关此问题的源代码可在我的网站上找到 我正在尝试使用中的以下代码向QTreeView模型动态添加一些项: 所以我需要想出左上和右下QModelIndex实例。如何从上述代码片段中的item1构建/获取这些 另外,我应该调用这些函数吗?来自QAbstractItemModel文档: void QAbstractItemModel::beginInsertRows ( const QModelIndex & parent, int first, int last ) [protected]

有关此问题的源代码可在我的网站上找到

我正在尝试使用中的以下代码向
QTreeView
模型动态添加一些项:

所以我需要想出
左上
右下
QModelIndex
实例。如何从上述代码片段中的
item1
构建/获取这些


另外,我应该调用这些函数吗?

来自QAbstractItemModel文档:

void QAbstractItemModel::beginInsertRows ( const QModelIndex & parent, int first, int last ) [protected]
Begins a row insertion operation.
When reimplementing insertRows() in a subclass, you must call this function before inserting data into the model's underlying data store.
The parent index corresponds to the parent into which the new rows are inserted; first and last are the row numbers that the new rows will have after they have been inserted.
其他受保护的函数也说了类似的事情

insertRows()表示:

如果您实现自己的模型,您可以在以下情况下重新实现此功能: 您希望支持插入。或者,您可以提供 拥有用于更改数据的API无论哪种情况,您都需要拨打 beginInsertRows()和endInsertRows()通知其他组件 模式已经改变

看看QabstracteModel和

视图连接到这些信号,以了解模型数据何时更改并重新排列内部数据。这些函数在内部发出信号,以便在视图发生时方便地发出警告。但信号只能由抽象类发出

与此信号相连的部件使用它来适应信号的变化 模型的尺寸。它只能由QAbstractItemModel发出 实现,并且不能在子类代码中显式发出

所以你必须坚持这些方法

编辑以回答您的评论:

事实上,项目应该有一个对模型的引用,并告诉它关于更改的信息,检查QStandardItem中的这些行:

(注意,在第二个示例中,它如何调用模型的rowsAboutToBeRemoved()和rowsRemoved())

也许你应该尝试使用和。
直接或子类化。它会隐藏很多丑陋的东西。

还有一种不太合适但更容易实现的方法-
emit layoutChanged()
而不是
dataChanged()
。更多信息-

通过插入的
行[aboutto]函数完成。那么,什么是
HidDescriptorTreeModel
?HidDescriptorTreeModel是从QAbstractItemModel继承的类?大家好,HidDescriptorTreeModel扩展了QabstracteModel,我将通过修改我的问题来提供更多细节。问题已经更新,带有指向BitBucket Git存储库的链接。我感谢您的评论。我的问题是理解在哪里调用begin/endInsertRows()。很容易说它需要在QAbstractItemModel中被调用,但是作为一个树结构,数据通常是通过appendChild()函数添加的,该函数是HidDescriptorTreeItem的一部分,因此需要以某种方式引用父树模型……我自己都搞糊涂了。:)非常有用,谢谢。我还发现了QT Creator附带的可编辑树模型示例。再加上你的回答,事情就清楚多了!不知道为什么这被否决了,这解决了我两天的虫子搜索!
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>());
void QAbstractItemModel::beginInsertRows ( const QModelIndex & parent, int first, int last ) [protected]
Begins a row insertion operation.
When reimplementing insertRows() in a subclass, you must call this function before inserting data into the model's underlying data store.
The parent index corresponds to the parent into which the new rows are inserted; first and last are the row numbers that the new rows will have after they have been inserted.