Qt QTreeView添加到模型时不更新
Qt QTreeView not updating when adding to model
与这个问题相关的源代码可以在我在BitBucket上的公共Git存储库中获得。
我试图在mainwindow.cpp中使用以下代码动态添加一些项目到QTreeView
模型:
if(dlg->exec() == QDialog::Accepted) {
QList<QVariant> qList;
qList << item.name << "1111 0000" << "0x00";
HidDescriptorTreeItem *item1 = new HidDescriptorTreeItem(qList, hidDescriptorTreeModel->root());
hidDescriptorTreeModel->root()->appendChild(item1);
}
当从我的MainWindow
构造器内运行时,就在ui->setupUi(this)
之后,但我需要从事件过滤器内运行,但相同的代码不会得到QTreeView
更新。当我在mainwindow.cpp:70
处设置一个断点并逐步执行接下来的几行时,我可以看到数据被添加到模型中,但我需要QTreeView
来刷新。
我理解这是通过发射dataChanged()
来完成的,但不确定如何做到这一点。dataChanged
信号的信号签名如下:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>());
所以我需要拿出topLeft
和bottomRight
QModelIndex
实例。我如何在上面的代码片段中从item1
构建/获取这些?
此外,beginInsertRows()
和endInsertRows()
在哪里进入这个视图,我应该调用这些函数吗?
摘自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()来通知其他组件模型变了
看一下QAbstractItemModel受保护的函数和信号
视图连接到这些信号,以知道模型数据何时更改并重新排列内部数据。这些函数在内部发出信号,以便在发生这种情况时方便地警告视图。但是信号只能由抽象类发出。
连接到该信号的组件使用它来适应环境的变化模型的尺寸。它只能由QAbstractItemModel发出不能在子类代码中显式地发出。
所以你必须坚持使用方法。
编辑回复你的评论:
确实,Items应该有一个对模型的引用,并告诉它关于更改,检查QStandardItem中的这些行:
空白QStandardItem: emitDataChanged ()
void QStandardItem::removeRows(int row, int count)
(注意,它如何在第二步调用模型的rowsabouttoberremoved()和rowsRemoved())
也许你应该尝试使用QStandardItem和QStandardItemModel。直接或子类化。它会隐藏很多难看的东西
还有一种不太合适但更容易实现这一点的方法- emit layoutChanged()
而不是dataChanged()
。更多信息- https://stackoverflow.com/a/41536459/635693
- 从C++本机插件更新Vector3数组
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- QTableView:endMoveRows在模型中重置水平页眉大小
- cmake更新缓存的变量
- 将IBM Rhapsody模型集成到VS 2019中
- 旋转模型矩阵时的形状失真
- 更新模型/视图方案中 QXXXView (QTableView, QTreeView,..) 元素的显示工具提示
- 从高度动态的C 数据模型中更新QML:计时器与属性绑定
- OpenGL-更新模型信息的最有效方法(例如模型矩阵)
- 根据用户的视图更改更新模型
- Qt模型视图:当数据存储和更改数据时,更新模型和视图的正确方法是什么::vector
- 在具有多行的 GtkTreeView 中,如何以编程方式更新特定行上的 GtkCellRendererCombo 模型
- 更改模型后视图未更新
- 图层下降和更新咖啡模型
- 在向模型添加新数据后,QML TreeView没有在运行时更新
- 视图类没有接收更新的模型类数据
- 更新FBX SDK模型加载从2012.2到2014.1 SDK
- Qt QTreeView添加到模型时不更新
- 从运行QML QtQuick2引擎的不同线程更新c++模型的行为
- 如何处理大容量模型更新场景中无响应的UI